# encoding: utf-8

class WebLink
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::MultiParameterAttributes
  
  
  has_one :name, :class_name => "I18nVariable", :as => :language_value, :autosave => true, :dependent => :destroy
  has_one :context, :class_name => "I18nVariable", :as => :language_value, :autosave => true, :dependent => :destroy
  
  has_and_belongs_to_many :tags, :class_name => "WebResourceTag"
  
  field :url
  field :create_user_id
  field :update_user_id
  
  field :is_top, :type => Boolean, :default => false 
  field :is_hot, :type => Boolean, :default => false 
  field :is_hidden, :type => Boolean, :default => false 
  
  belongs_to :web_link_category
  
  validates_presence_of :name
  
  before_save :set_key

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

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


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

  end

  def is_top?
    self.is_top
  end
  
  def name
    @name ||= I18nVariable.first(:conditions => {:key => 'name', :language_value_id => self.id, :language_value_type => self.class}) rescue nil
  end
  
  def context
    @context ||= I18nVariable.first(:conditions => {:key => 'context', :language_value_id => self.id, :language_value_type => self.class}) rescue nil
  end
  
  def text
    @text ||= I18nVariable.first(:conditions => {:key => 'text', :language_value_id => self.id, :language_value_type => self.class}) rescue nil
  end  

  def sorted_tags
    tags.order_by(I18n.locale, :asc)
  end
  
  protected
  
  def set_key
    if name && name.new_record?
      name.key = 'name'
    end
    if context && context.new_record?
      context.key = 'context'
    end
  end
  
end