class Design
  include Mongoid::Document
  include Mongoid::Timestamps
  include ParserLayout

  field :title, :type => String
  field :author, :type => String
  field :intro, :type => String
  field :version, :type => String

  has_many :pages
  
  embeds_one :layout, :cascade_callbacks => true
  embeds_one :default_css, :class_name => "Stylesheet", :cascade_callbacks => true
  embeds_one :reset_css, :class_name => "Stylesheet", :cascade_callbacks => true
  embeds_many :themes, :cascade_callbacks => true
  embeds_many :javascripts, :cascade_callbacks => true
  embeds_many :images, :as => :design_image, :cascade_callbacks => true
  # embeds_many :custom_images, :class_name => 'Image', :cascade_callbacks => true
  
  validates_presence_of :title
  validates_presence_of :author
  
  after_save :parse_css_for_images
 
  def new_files=(*attrs)
    attrs[0].map  do |key,items_ary|   #Loop by JSs,Themes,Imgs
        self.files=([items_ary, key])
    end
  end
 
  # def javascripts=(*attrs)
  #   self.files = (attrs << 'javascripts')
  # end
  # 
  # def themes=(*attrs)
  #   self.files = (attrs << 'themes')
  # end
  # 
  # def images=(*attrs)
  #   self.files = (attrs << 'images')
  # end
  
  # Update or create the attribute records
  def files=(attrs)
    case attrs.last
      when 'layout'
        files = self.layout.build
      else
        files = eval(attrs.last)
    end
    attrs[0].each do |a|
       
      if a[:id].blank? && !a[:file].blank?
        files.build(:file => a[:file], :to_save => true)
      else
        files.each do |file|
          if file.id.to_s == a[:id]
             file.to_destroy = a[:to_destroy]
          end
        end
      end
    end
  end
  
  protected
  
  def parse_css_for_images
    if (self.default_css && self.default_css.changed)
      self.default_css.parse_urls
    end
    self.themes.each do |theme|
      if theme.changed?
        theme.parse_urls
      end
    end
    parse_body_for_images(self)
  end
  
end
