# encoding: utf-8

class NewsBulletin
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::MultiParameterAttributes  
  include Sunspot::Mongo
  include Impressionist::Impressionable

  BelongsToCategory =  :news_bulletin_category
  include OrbitCoreLib::BelongsToCategoryMayDisable
  include OrbitCoreLib::Preview
#  include Tire::Model::Search
 # include Tire::Model::Callbacks
  # include Redis::Objects




  #scope :searchable,where(:is_checked=>true,:is_hidden=>false,:is_pending=>false)

  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 => "NewsTag"

  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
  
  belongs_to :unit_list_for_anc
  
  # embeds_many :news_bulletin_links, :cascade_callbacks => true
  # embeds_many :news_bulletin_files, :cascade_callbacks => true

  has_many :news_bulletin_links, :autosave => true, :dependent => :destroy
  has_many :news_bulletin_files, :autosave => true, :dependent => :destroy
  
  accepts_nested_attributes_for :news_bulletin_files, :allow_destroy => true
  accepts_nested_attributes_for :news_bulletin_links, :allow_destroy => true
  
  validates :title, :at_least_one => true
  
  before_save :check_deadline
  before_save :update_avliable_language, :clean_tags
  
  after_save :save_news_bulletin_links
  after_save :save_news_bulletin_files

    # Tire.index 'news_bulletin' do
    #   delete
    #   create :mappings =>{
    #     :news_bulletin_by_title => {
    #       :properties=> {
    #         :title => { :type => 'string', :index => 'not_analyzed', :include_in_all => false },
    #         :body => {}
    #       }
    #     }
    #     :news_bulletin_by_body => {
    #       :properties=> {
    #         :body => { :type => 'string', :index => 'not_analyzed', :include_in_all => false },
    #       }
    #     }
    #   }
    #  end
  # mapping do
  #   indexes :title,        :analyzer => 'cjk', :boost => 10
  #   indexes :sub_titles,        :analyzer => 'cjk', :boost => 5
  #   indexes :text,           :analyzer    => 'cjk'
  # end
  def type
    "news_bulletin"
  end

  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
    integer :view_count
    
    string :available_lang , :multiple => true do
      VALID_LOCALES.collect{|t| enabled_for_lang(t.to_sym) ? t : nil}.delete_if{|t| t.nil?}
    end

    boolean :frontend_search do
      ( !is_hidden &&  !is_pending && is_checked && !is_rejected )
    end
    
    
    string :news_bulletin_category_id
    end

 # redis_search_index(:title_field => :s_title,
 #                      :alias_field =>  :s_title_en,
 #                     :score_field => :view_count,
 #                     :condition_fields => [:is_checked,:is_hidden,:news_bulletin_category_id,:is_pending],
 #                     :ext_fields =>[])

#  def gen_title_for_search
#   # [s_title,s_title_en,s_text_en,s_text_zh_tw].join(' ')
# end

 #  def s_title
 #   self.
 #  end

 # def s_title_was
 #   self.title_was["zh_tw"]
 # end

 #  def s_title_en
 #   self.title_translations["en"]
 #  end

 # def s_title_en_was
 #   self.title_was["en"]
 #  end

 # def s_text_en
 #  Nokogiri::HTML(self.text.en).text
 # end
 # def s_text_zh_tw
 #  Nokogiri::HTML(self.text.zh_tw).text
 # end
  def share_item
      Item.first(conditions:{name: 'news'})
  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 => {news_bulletin_category_id: category_id}).any_of( {deadline: nil,:postdate.lte => date_now} , {:deadline.gte => date_now,:postdate.lte => date_now} ).any_of(is_hot: true, is_top: true).desc(:postdate)
   else
     any_of( {deadline: nil,:postdate.lte => date_now} , {:deadline.gte => date_now,:postdate.lte => date_now} ).any_of(is_hot: true, is_top: true).desc(:postdate)
   end
   
  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 enabled_for_lang(lang)
    eval("self.available_for_#{lang}")
  end

  def de_pending
    self.is_pending = false
  end

  def de_pending!
    de_pending
    self.save!
  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_news_bulletin_links
	self.news_bulletin_links.each do |t|
	  if t.should_destroy
		t.destroy
	  end
    end
  end
  
  def save_news_bulletin_files
	self.news_bulletin_files.each do |t|
	  if t.should_destroy
		t.destroy
	  end
    end
  end

  def self.filter(news_bulletins)
    news_bulletins.each do |news_bulletin|
      p "#{news_bulletin.id}/#{news_bulletin.is_top}/#{news_bulletin.is_hot}/#{news_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_news_front_end_news_bulletin_path",:object_class_type=>"NewsBulletin")
    preview_object.preview_files.build(:file=>self.news_bulletin["image"],:field_name_for_rebuild=>'image')


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

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

    preview_object.object = self.news_bulletin.except("news_bulletin_files_attributes","image","news_bulletin_links_attributes")
    preview_object
  end
  
  protected
  
  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 check_deadline
    if(!self.deadline.nil? and (self.deadline < self.postdate ))
      self.deadline = nil
    end
  end

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



end
