class Item

  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Tree
  include Mongoid::Tree::Ordering
  LIST = YAML.load(File.read("#{Rails.root}/config/list.yml"))

  field :name
  field :path
  field :is_published, :type => Boolean, :default => false
  field :enabled_for, :type => Array, :default => nil
  field :menu_enabled_for, :type => Hash, :default => nil
  field :title, localize: true
  field :sitemap_enabled, :type => Hash, :default => {}

 
  validates_format_of :name, :with => /^[0-9a-zA-Z\-_]+$/
  # validates :name, :exclusion => { :in => LIST[:forbidden_item_names] }
  validates_uniqueness_of :name #, :scope => :parent_id
  validates_presence_of :name
  validates_associated :parent, :children
  
  before_destroy :destroy_children
  after_rearrange :rebuild_path, :if => "parent_id_changed? || name_changed?"
  after_save :rebuild_children_path, :if => "path_changed?"
  
  def enabled_for_lang(lang)
    enabled_for.include?(lang) rescue false
  end

  def self.find_by_name(item_name)
    Item.first(:conditions => { :name => item_name, :is_published => true })
  end

  def visible_children
    objects = self.children
    a = []
    if objects
      objects.each do |object|
        a << object if object.menu_enabled_for.nil? ? true : object.menu_enabled_for[I18n.locale.to_s].eql?("true")
      end
    end
    a
  end

  def find_by_parent_and_position(parent, position)
    parent.children.detect{|child| child.position == position}
  end


   def shift_to(new_parent, position, next_sibling_id)
    position = position.to_i
    new_parent = Item.find(new_parent)
    
    if next_sibling_id
      next_sibling = Item.find(next_sibling_id)
      self.move_above(next_sibling)
    else
      self.move_to_bottom
    end

    if self.parent != new_parent
      self.parent = new_parent
      save
    end
  end

  def show_in_sitemap_for(locale)
    if !sitemap_enabled.blank? && !sitemap_enabled[locale].blank?
      sitemap_enabled[locale].eql?('true') ? true : false
    else
      true
    end
  end

  def self.structure_ordered_items
    self.get_children(Item.root, [])
  end
  
  protected
  
  def rebuild_path
    self.path = (self.ancestors_and_self - [Item.root]).collect{|x| x.name unless x.root?}.join('/')
  end

  def rebuild_children_path
    self.children.each do |child|
      child.path = (child.ancestors_and_self - [Item.root]).collect{|x| x.name}.join('/')
      child.save
      child.rebuild_children_path
    end
  end

  # Enable the validation for parent_id
  def validates_presence_of_parent_id?
    true
  end

  def self.get_children(item, tree)
    tree << item
    item.children.each do |child|
      self.get_children(child, tree)
    end
    tree
  end
    
end
