# encoding: utf-8
class WebLink
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::MultiParameterAttributes
  include Sunspot::Mongo

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

  field :title, localize: true
  field :context, localize: true
  
  field :url, localize: true
  field :create_user_id
  field :update_user_id, :class_name => "User"
  
  scope :can_display,where(is_hidden: false)
  
  # belongs_to :web_link_category
  
  before_save :clean_tags

  validates :title, :at_least_one => true

  before_validation :add_http
  # validates :url, :presence => true, :format => /^(http|https):\/\/(([a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5})|((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(:[0-9]{1,5})?(\/.*)?/i

  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, :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 add_http
    unless self.url[/^http:\/\//] || self.url[/^https:\/\//]
      self.url = 'http://' + self.url
    end
  end

  def clean_tags
    self.tagged_ids.delete('')
  end
  
end