# encoding: utf-8
# require "impressionist"
class Bulletin
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::MultiParameterAttributes
  include Sunspot::Mongo
  include Impressionist::Impressionable

  BelongsToCategory =  :bulletin_category
  include OrbitCoreLib::BelongsToCategoryMayDisable
  include OrbitCoreLib::Preview

  is_impressionable :counter_cache => { :column_name => :view_count }

  field :title, localize: true
  field :subtitle, localize: true
  field :text, localize: true

  has_and_belongs_to_many :tags, :class_name => "AnnouncementTag"

  field :postdate , :type => DateTime
  field :deadline , :type => DateTime
  # field :url

  field :create_user_id
  field :update_user_id, :class_name => "User"
  
  field :is_top, :type => Boolean, :default => false
  field :is_hot, :type => Boolean, :default => false
  field :is_hidden, :type => Boolean, :default => false
  field :is_checked, :type => Boolean, :default => false
  field :is_pending, :type => Boolean, :default => true 
  field :is_rejected, :type => Boolean, :default => false 
  field :view_count, :type => Integer, :default => 0
  
  field :not_checked_reason
  
  field :public, :type => Boolean, :default => true
  
  scope :can_display, where(is_checked: true, is_rejected: false, is_pending: false)
  scope :available_for_lang, ->(locale){ where("available_for_#{locale}".to_sym => true) }

  mount_uploader :image, ImageUploader

  has_many :bulletin_links, :autosave => true, :dependent => :destroy
  has_many :bulletin_files, :autosave => true, :dependent => :destroy
  
  accepts_nested_attributes_for :bulletin_files, :allow_destroy => true
  accepts_nested_attributes_for :bulletin_links, :allow_destroy => true
  
  validates :title, :at_least_one => true

  before_save :check_deadline, :update_avliable_language, :clean_values#, :save_bulletin_links, :save_bulletin_files

  searchable do
    text :titles do
      title_translations.to_a.collect{|t| t[1]}
    end
    text :texts do
      text_translations.to_a.collect{|t| Nokogiri::HTML(t[1]).text}
    end
    
    string :available_lang , :multiple => true do
      VALID_LOCALES.collect{|t| enabled_for_lang(t.to_sym) ? t : nil}.delete_if{|t| t.nil?}
    end

    # text :text do
    #   a = (title_translations["zh_tw"] + title_translations["en"])
    #   a
    # end
    boolean :frontend_search do
      ( !is_hidden &&  !is_pending && is_checked && !is_rejected )
    end

    integer :view_count
    string :bulletin_category_id
    end
  
  def share_item
      Item.first(conditions:{name: 'announcement'})
  end  

  def proc_check(check,not_pass_info = "")
    self.is_checked = true
      if check =="true"
        self.is_rejected = false
      elsif check == "false"
        self.is_rejected = true
        self.not_checked_reason = not_pass_info
      end
  end

  def de_pending
    self.is_pending = false
  end

  def de_pending!
    de_pending
    self.save!
  end

  def enabled_for_lang(lang)
    eval("self.available_for_#{lang}")
  end

  def publish_month
    published_at.strftime("%B %Y")
  end

  def self.search( search = nil, category_id = nil )
    if category_id.to_s.size > 0 and search.to_s.size > 0
      key = /#{search}/
      find(:all, :conditions => {title: key, bulletin_category_id: category_id}).desc( :is_top, :postdate )
    elsif category_id.to_s.size > 0 and search.to_s.size < 1
      find(:all, :conditions => {bulletin_category_id: category_id}).desc( :is_top, :postdate )
    elsif search.to_s.size > 0 and category_id.to_s.size < 1
      key = /#{search}/
      find(:all, :conditions => {title: key}).desc( :is_top, :postdate )
    else
      find(:all).desc( :is_top, :postdate)
    end
  end


  def self.widget_datas( category_id = nil )
  
    date_now = Time.now
 
   # find(:all, :conditions => {:postdate => {"$lte" => Date.today}, deadline: nil} ).desc( :is_top, :postdate)
   # where( :postdate.lte => date_now ).where( :deadline => nil ).desc(:is_top, :postdate)
   # any_of({ :title => "test" },{:deadline => nil, :title => "123"})
   
   if category_id.to_s.size > 0
     find(:all, :conditions => {bulletin_category_id: category_id}).any_of( {deadline: nil,:postdate.lte => date_now} , {:deadline.gte => date_now,:postdate.lte => date_now} ).desc( :is_top, :postdate)
   else
     any_of( {deadline: nil,:postdate.lte => date_now} , {:deadline.gte => date_now,:postdate.lte => date_now} ).desc( :is_top, :postdate)
   end
   
  end

  def is_expired?
    Date.today > self.deadline ? true : false  rescue false
    #some dates might sat as nil so rescue false
  end

  def is_top?
    self.is_top
  end
  
  def is_hot?
    self.is_hot
  end
  
  def is_hidden?
    self.is_hidden
  end

  def is_checked?
    !self.is_pending && self.is_checked && (self.is_rejected == false)
  end
  
  def is_pending?
    self.is_pending
  end
  
  def is_rejected?
    !self.is_pending && self.is_rejected && (self.is_rejected == true)
  end
  
  
  def save_bulletin_links
	self.bulletin_links.each do |t|
	  if t.should_destroy
		t.destroy
	  end
    end
  end
  
  def save_bulletin_files
	self.bulletin_files.each do |t|
	  if t.should_destroy
		t.destroy
	  end
    end
  end

  def self.filter(bulletins)
    bulletins.each do |bulletin|
      p "#{bulletin.id}/#{bulletin.is_top}/#{bulletin.is_hot}/#{bulletin.is_hidden}"
    end
    return nil
  end

  def sorted_tags
    tags.order_by(I18n.locale, :asc)
  end
  

  def to_preview
    preview_object = Preview.new(:expired_at=>DateTime.now+30.minutes,:preview_at_link=>"panel_announcement_front_end_bulletin_path",:object_class_type=>"Bulletin")

    self.bulletin["bulletin_files_attributes"].each_with_index do |atr,idx| 
      preview_object.preview_files.build(:file=>self.bulletin["bulletin_files_attributes"][idx.to_s],:field_name_for_rebuild=>'bulletin_files',:file_in_array=>true)
    end unless self.bulletin["bulletin_files_attributes"].nil?

    self.bulletin["bulletin_links_attributes"].each_with_index do |atr,idx| 
      preview_object.preview_associations.build(:object=>self.bulletin["bulletin_links_attributes"][idx.to_s],:field_name_for_rebuild=>'bulletin_links',:object_in_array=>true)
    end unless self.bulletin["bulletin_links_attributes"].nil?


    preview_object.object = self.bulletin.except("bulletin_files_attributes","bulletin_links_attributes")
    preview_object
  end


  protected
  
  def check_deadline
    if(!self.deadline.nil? and (self.deadline < self.postdate ))
      self.deadline = nil
    end
  end
  
  def update_avliable_language
    VALID_LOCALES.each  do |locale|
      if (title_translations[locale].blank? rescue true)
        self["available_for_#{locale}".to_sym] = false 
      else
        self["available_for_#{locale}".to_sym] = true
      end
    end
  end

  def clean_values
    self.bulletin_links.each do |link|
      link.delete if link.url.blank? && link.title.blank?
    end
    self.tag_ids.delete('')
  end


end
