# encoding: utf-8

class Qa
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::MultiParameterAttributes

  include OrbitModel::LanguageRestrict
  include OrbitModel::Status
  include OrbitTag::Taggable
  include OrbitCategory::Categorizable

  field :title, localize: true
  field :answer, localize: true

  field :create_user_id
  field :update_user_id

  has_many :qa_links, :autosave => true, :dependent => :destroy
  has_many :qa_files, :autosave => true, :dependent => :destroy
  
  accepts_nested_attributes_for :qa_files, :allow_destroy => true
  accepts_nested_attributes_for :qa_links, :allow_destroy => true
  
  # belongs_to :qa_category
  
  before_save :clean_values

  validates :title, :at_least_one => true


  def self.search( category_id = nil )
  
	if category_id.to_s.size > 0
	
	  find(:all, :conditions => {qa_category_id: category_id}).desc( :is_top, :title )

	else
	  
	  find(:all).desc( :is_top, :title)
	  
	end
	
  end


  def self.widget_datas
  
	where( :is_hidden => false ).desc(:is_top, :created_at)

  end

  protected

  def qa_category_with_title
    self.category.title
  end

  def clean_values
    self.qa_links.each do |link|
      link.delete if link.url.blank? && link.title.blank?
    end
    self.tagged_ids.delete('')
  end
  
  paginates_per 10
end