class Page < Item
  
  field :content
  field :app_frontend_url
  field :theme_id, :type => BSON::ObjectId, :default => nil
  
  belongs_to :design
  belongs_to :module_app
  has_one :title, :class_name => "I18nVariable", :as => :language_value, :autosave => true, :dependent => :destroy
  has_many :page_parts, :autosave => true, :dependent => :destroy
  has_many :page_contexts, :autosave => true, :dependent => :destroy
  has_many :page_metas, :autosave => true, :dependent => :destroy
  accepts_nested_attributes_for :page_parts, :allow_destroy => true
  
  before_save :create_parts, :set_key
  
  # embeds_many :custom_images, :class_name => 'Image', as: :design_image
  
  def is_home?
    self.parent ? false : true
  end

  def title
    @title ||= I18nVariable.first(:conditions => {:key => 'title', :language_value_id => self.id, :language_value_type => self.class}) rescue nil
  end
  
  protected
  
  def create_parts
    page_design = self.design
    page_design.layout.layout_parts.each do |layout_part|
      self.page_parts.new(:name => layout_part.name) unless self.page_parts.detect{|page_part| page_part.name.eql?(layout_part.name)}
    end
  end
  
  def set_key
    if title && title.new_record?
      title.key = 'title'
    end
  end
  
end
