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

  field :name
  field :content, localize: true
  field :kind, default: "none"
  field :public_r_tag
  field :public_r_tag_object_id, :default => nil
  field :public_r_tag_option, :default => nil
  field :page_title, localize: true
  field :widget_path
  field :category,type: Array, :default => []
  field :tag, type: Array,:default => []
  
  field :widget_style
  field :widget_field , :type => Array,:default => []

  field :widget_field_name , :type => Array,:default => []
  field :widget_class , :type => Array,:default => []
  field :widget_sat_to_link , :type => Array,:default => []
  
  field :widget_options ,:type=>Hash
  field :widget_data_count

  belongs_to :page
  belongs_to :module_app

  before_save :delete_empty_widget_field
  after_save :update_parent

  def default_widget_field_sat_to_link?(i)
    case widget_sat_to_link[i]
      when 'true'
        true
      when 'false'
        false
      else
        nil
    end
  end

  def default_widget_field_name
    return widget_field_name
  end

  def widget_field=(settings)
    settings.each_with_index do |setting,index|
      self.widget_field_name[index] =  setting["field_name"]
      self.widget_class[index] = setting["class"]
      self.widget_sat_to_link[index] = setting["sat_to_link"]
    end
  end

  def edit_title
    case self.kind
    when 'text'
      I18n.t(:text)
    when 'public_r_tag'
      self.public_r_tag.humanize
    when 'module_widget'
      self.module_app.title rescue I18n.t(:undefined)
    else
      I18n.t(:undefined)
    end
  end

  protected
  
  def delete_empty_widget_field
  	if self.widget_field
        self.widget_field.reject! { |wf| (wf[0].blank? || wf[1].blank?) }
  	end
    # self.widget_field.delete("") if self.widget_field
  end

  def update_parent
    self.page.save
  end

end