class PagePart
   
  include Mongoid::Document
  include Mongoid::Timestamps

  field :name
  field :content
  field :kind
  field :i18n_variable_id, :type => BSON::ObjectId

  belongs_to :page
  
  # Get the i18n_variable
  def i18n_variable
    @i18n_variable ||= I18nVariable.find(self.i18n_variable_id) rescue nil
  end
  
  # Update or create the i18n_variable record
  def i18n_variable=(attr)
    if self.i18n_variable_id
      self.i18n_variable.update_attributes(attr)
    else
      var = I18nVariable.new(attr.merge({:key => self.name, :document_class => self.class, :parent_id => self.page.i18n_variable_id}))
      var.save
      self.i18n_variable_id = var.id
    end
  end
  
  def destroy_i18n_variable
    self.i18n_variable.destroy rescue nil
  end
  
  # Build the content from the i18n_variable
  def build_content(locales)
    res = ''
    res << "<r:multi_lang i18n_id='#{i18n_variable.id}'>"
    locales.each do |locale|
      res << "<r:lang name='#{locale.to_s}'>"
      res << i18n_variable[locale.to_s]
      res << "</r:lang>"
    end
    res << "</r:multi_lang>"
    self.content = res
  end

end