class Product
  include SimplyStored::Couch
  include ActiveModel::SerializerSupport
  include Paperclip::Glue

  property :name
  property :code
  property :price, type: Float
  property :description
  property :visible, type: :boolean, default: true
  property :active, type: :boolean, default: true
  property :position, type: Fixnum

  belongs_to :product_category
  #has_and_belongs_to_many :product_categories, storing_keys: false
  has_and_belongs_to_many :product_labels, storing_keys: false
  belongs_to :supplier # direct! category is an aid
  has_many :product_orders
  has_many :product_variants, dependent: :destroy

  attr_protected :supplier_id

  validates :name, presence: true
  validates :supplier_id, presence: true
  validates :price, numericality: true
  view :by_supplier_id_and_id, key: [:supplier_id, :_id]
  view :by_product_category_id, key: :product_category_id

  #after_save :persist_product_category_ids

  #def product_category_ids=(ids)
    #@product_category_ids = ids.select(&:present?)
    #is_dirty
  #end

  #def product_category_id=(id)
    #self.product_category_ids = [id]
  #end

  property :image_file_name
  property :image_content_type
  property :image_file_size, :type => Fixnum
  property :image_updated_at, :type => Time
  has_attached_file :image,
    url: '/system/product/:id/images/:style.:extension',
    styles: {medium: '512x512>', thumb: '128x128>', large: '896x896>', small: '320x320>'},
    default_url: '/assets/user/blank-pixel.png'
  validates_attachment :image, content_type: {content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"]}


#private

  #def persist_product_category_ids
    #return unless defined?(@product_category_ids) # Do not do anything if nothing happened to this attribute
    #@product_category_ids ||= []
    #existing_product_categories = product_categories

    ## do nothing if nothing has changed
    #return if @product_category_ids == existing_product_categories.map(&:id)

    ## clear removed product categories
    #existing_product_categories.reject{|pc| @product_category_ids.include?(pc.id) }.each{|pc| pc.remove_product(self) }


    ## Add product to newly added product categories
    #database.load(@product_category_ids - existing_product_categories.map(&:id)).each do |product_category|
      #product_category.add_product(self)
    #end
  #end

end
