# -*- encoding : utf-8 -*-
class MenuItem < ActiveRecord::Base
  
  ContentTypes =[
    {:slug => "Page", :name => "page"},
    {:slug => "MenuAlias", :name => "Alias"},
    {:slug => "MenuUrl", :name => "Lien externe"},
    {:slug => "Article", :name => "Lien vers un article"},
  ] 
  
  
  
  has_many :popup_popupables, :as => :popupable
  has_many :popups, :through => :popup_popupables
  
	has_many :animal_animalables, :as => :animalable
	has_many :animals, :through => :animal_animalables 
  
	has_many :category_categoryables, :as => :categoryable
	has_many :categories, :through => :category_categoryables 
  
  has_many :menu_item_tags
  has_many :tags, :through => :menu_item_tags
  
  has_many :menu_item_articles
  has_many :articles, :through => :menu_item_articles
  
  has_many :menu_item_categories
  #has_many :categories, :through => :menu_item_categories
  
  include Rails.application.routes.url_helpers
  
  belongs_to :menu_content, :polymorphic => true
  belongs_to :menu
  #validates :name, :presence => true
  #validates :slug, :presence => true
  has_many :menu_item_langs, :dependent => :destroy
  
  accepts_nested_attributes_for :menu_content
  
  accepts_nested_attributes_for :menu_item_langs

  belongs_to :image_file
  belongs_to :icon_image_file, :class_name => "ImageFile"
  belongs_to :icon_b_image_file, :class_name => "ImageFile"
  belongs_to :icon_v_image_file, :class_name => "ImageFile"

  attr_accessor :skip_before_update, :skip_permalink, :ancestors_menu, :skip_index
  
  #after_update do
  #  if !skip_index
  #    logger.debug ["Updating document... ",  self.menu_content.__elasticsearch__.delete_document, self.menu_content.__elasticsearch__.index_document].join
  #  end
     
  #end
  
	def name
    self.menu_item_langs.first.name
  end

  acts_as_tree
  
  
  
  def select_lang(lang_site_id)
    self.menu_item_langs.find_by_lang_site_id(lang_site_id)
  end
  

  def url
    if menu_content
      self.permalink
      
    else
      "/404.html"
    end
  end
  
  def cible_url(lang)
    menu_item_path(:url => self.menu_item_langs.find_by_lang_site_id(lang.id).permalink, :lang => lang.slug)
  end

  


  def generate_permalink(menu_item_lang)
    r = ""
    
    node, ancestors = self, []
    ancestors << node = MenuItem.find(node.parent_id) while node.parent_id?
          
    
    
    ancestors.reverse.each do |ancestor|
      r += ancestor.select_lang(menu_item_lang.lang_site_id).slug.to_s
      r+= "/"
    end
    r+= menu_item_lang.slug.to_s
  end
  
  def set_permalink
    
    
    if !skip_permalink
      
      
      
      self.menu_item_langs.each do |menu_item_lang|
        menu_item_lang.permalink = self.generate_permalink(menu_item_lang)
        menu_item_lang.save
      end
      
      #self.skip_permalink = true
      #self.skip_before_update = true
      
      
      
      #self.save
    
    
    #  self.children.each do |child|        
    #    child.save
    #  end
    end
    
  end
  
  
  
  def validate_permalink
    self.parent_id = nil if self.parent_id == 0
    errors.add(:parent_id, 'doit être différent de la page actuelle') if parent_id == id and id != nil
    
    if self.id
      errors.add(:parent_id, 'attention la page parente à pour page parente celle-ci = boucle') if self.parent_id and self.id == MenuItem.find(self.parent_id).parent_id
    end

    conditions = ["menu_id = ? and parent_id "+(self.parent_id ? "=" : "IS")+" ? and slug = ? "+("and id != ?" if self.id).to_s, self.menu_id,self.parent_id ,self.slug]
    conditions << self.id if self.id
    if MenuItem.where(conditions).first
      errors.add(:slug, 'est déjà utilisé') 
      
    end
    

  end
  
  
  def cible_name
    "Elément de menu : #{self.name}"
  end



  before_create do
    if !position
      top = MenuItem.where(:parent_id => self.parent_id, :menu_id => self.menu_id).order("position DESC").first
      if top
        self.position = top.position.to_i + 1
      else
        self.position = 1
      end
    end
    
  end

  before_update do
  
      if self.parent_id_changed?
        
        MenuItem.where(["menu_id = ? and position > ? and parent_id "+(self.changes['parent_id'][0] ? "=" : "IS")+" ?",self.menu_id,self.position,self.changes['parent_id'][0]]).each do |portlet|
          portlet.position = portlet.position - 1
          portlet.save!
        end
        
        self.position = 1
        
        MenuItem.where(["menu_id = ? and parent_id "+(self.parent_id ? "=" : "IS")+" ?",self.menu_id,self.parent_id]).each do |portlet|
          portlet.position = portlet.position + 1

          portlet.save!
        end
        
        
        
        
      
    end
  end

  before_destroy do
    MenuItem.where(["menu_id = ? and position > ? and parent_id "+(self.parent_id ? "=" : "IS")+" ?",self.menu_id,self.position,self.parent_id]).each do |portlet|
      portlet.position = portlet.position - 1
      portlet.skip_before_update = true
      portlet.save!
    end

  end
  
  after_save do
    if menu_content_type == "Page"
      self.menu_content.skip_save_menu_item = true
      self.menu_content.save
    
    end
      
  end
  
  scope :archived, -> {where("archived = ?",true )}
  scope :unarchived, -> {where(:archived => nil )}
  
  
  
  


end
