class Manufacturer < ActiveRecord::Base
  attr_accessible :body, :description, :logotype_uri, :logotype_uri_cache, :partner, :published, :title

  has_many :products, :dependent => :destroy

  mount_uploader :logotype_uri, ManufacturerLogotypeUploader

  validates_length_of :description, :maximum => 1024

  validates_presence_of :title
  validates_length_of :title, :maximum => 255

  default_scope order('title ASC')
  scope :visible_to_user, where(:published => true)
  scope :visible_to_user_partners, visible_to_user.where(:partner => true)

  define_index do
    indexes title, :sortable => true
    #indexes description
    #indexes body
    has published
    has partner
    #TODO set_property delta: true # 'delta:boolean' column should present
    #set_property field_weights: {
    #    title: 3,
    #    description: 1,
    #    body: 1
    #}
  end

  sphinx_scope(:sphinx_default_scope) {
    {order: 'title ASC', star: true}
  }

  default_sphinx_scope :sphinx_default_scope

  def self.readable_collection
    select([:id, :title]).sort_by {|o| o.title }
  end

  # @return [Array] 8 random partners with id and image
  def self.random_partners
    select([:id, :logotype_uri]).find(visible_to_user_partners.pluck(:id).sample(8)).shuffle
  end

end
