class WritingJournal
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::MultiParameterAttributes

  LANGUAGE_TYPES = [ "English", "Chinese" ]

  field :paper_title, localize: true
  field :journal_title, localize: true
  field :authors, localize: true

  has_and_belongs_to_many :tags, :class_name => "PersonalJournalTag"
  has_and_belongs_to_many :journal_author_types
  has_and_belongs_to_many :journal_level_types
  has_many :writing_journal_files, :autosave => true, :dependent => :destroy
  belongs_to :journal_paper_type

  field :year
  field :language
  field :isbn
  field :vol_no
  field :issue_no
  field :form_to_start
  field :form_to_end
  field :total_pages
  field :keywords
  field :abstract
  field :publication_date, :type => Date
  field :url
  field :note
  field :create_user_id, :type => BSON::ObjectId
  field :update_user_id, :type => BSON::ObjectId


  accepts_nested_attributes_for :writing_journal_files, :allow_destroy => true
  after_save :save_writing_journal_files
  before_validation :add_http
  before_save :save_co_author
  validates :paper_title, :at_least_one => true
  validates :url, :format => /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/ix, :unless => Proc.new{self.url.blank?}

  def save_co_author
    authors_list = authors.split(",").map{|n| n.strip.gsub(/\s+/," ")}.reject{|n| n.empty? }
    if new_record?
      current_user = create_user_id
    else
      current_user = update_user_id
    end

    authors_db = CoAuthor.where(:name_id => current_user).map(&:co_author)
    authors_list.delete(User.find(current_user).name)
    authors_list = authors_list.delete_if{|author| authors_db.include?author}
    authors_list.each do |author|
      CoAuthor.new(:co_author => author, :name_id => current_user).save
    end
  end

  def self.search( category_id = nil )
    if category_id.to_s.size > 0
      find(:all, :conditions => {writing_journal_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

  def is_top?
    self.is_top
  end

  def sorted_tags
    tags.order_by(I18n.locale, :asc)
  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 save_writing_journal_files
    self.writing_journal_files.each do |t|
      if t.should_destroy
        t.destroy
      end
    end
  end

  def create_link
    title = ["\"#{self.paper_title}\""]
    title << self.journal_title
    title.join(', ')
    title << ( !self.journal_level_types.blank? ? "(#{self.journal_level_types.collect{|x| x.title}.join(', ')})" : nil)
    title.join(', ')
  end

  def new_writing_journal_files=(var)
    self.writing_journal_files.new(:file=>var[0])
  end
  protected

  def add_http
    unless self.url.blank? || self.url[/^http:\/\//] || self.url[/^https:\/\//]
      self.url = 'http://' + self.url
    end
  end

  def clean_checkboxs
    self.tag_ids.delete('')
    self.journal_author_type_ids.delete('')
    self.journal_level_type_ids.delete('')
  end
end
