#require 'elasticsearch/model'




# -*- encoding : utf-8 -*-
class Page < ActiveRecord::Base
  searchkick # default_fields: [:html1, :title1, :description1]
  
  #include Elasticsearch::Model
  #include Elasticsearch::Model::Callbacks
  
  
  attr_accessor :skip_save_menu_item
  
  
  PAGE_TYPE = [["Page simple", 1], ["Page chapitrée", 2], ["Chapitre", 3], ["Page thématique", 4]]
  
  
  has_many :lang_pages
  
  accepts_nested_attributes_for :lang_pages
  
  
  has_one :menu_item, :as => :menu_content
  
  has_many :blocks, :as => :blockable, :dependent => :destroy
  
  after_save do
    if !self.skip_save_menu_item
      if self.menu_item
        self.menu_item.updated_at = Time.now
        self.menu_item.save
      end
    
    end
  end
  
  
  #validates :title, :presence => true
  
  HUMAN_NAME = "Page"
  
  after_create :after_creation
  
  def after_creation
      
    LangSite.all.each do |lang|
      @block = Block.new(:block_name => "general", :lang_site => lang)
      @block.blockable = self
      @block.save
      
    end
  
  
  end
  
  
  
  def dup
    @new = Page.new(self.attributes)
    @new.id = nil
    @new.save
    @new.blocks.destroy_all
    
    self.lang_pages.each do |lang_page|
      
      new_p = lang_page.dup
      
      new_p.title = lang_page.title+" copie"
      new_p.page = @new
      new_p.save
      
      
    end
    
    self.blocks.each do |block|
      
      new_b = block.dup
      new_b.blockable = @new
      new_b.save
      
      
    end
    
    @new
    
  end

  def search_data
    { 
      html: lang_pages.map(&:html),
      title: lang_pages.map(&:title),
      description: lang_pages.map(&:description),

      created_at: created_at
      
      
      
    }
  end



  def as_indexed_json(options={})
    self.as_json(
      include: { lang_pages: { methods: [:html], only: [:title, :description, :html]}#,
                # authors:    { methods: [:full_name], only: [:full_name] },
                # comments:   { only: :text }
               })
  end

end

#Page.import
