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

  include OrbitModel::LanguageRestrict
  include OrbitModel::Status
  include OrbitTag::Taggable

  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_and_belongs_to_many :journal_co_authors
  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
  
  paginates_per 10

  accepts_nested_attributes_for :writing_journal_files, :allow_destroy => true
  after_save :save_writing_journal_files
  before_validation :add_http
  validates :paper_title, :at_least_one => true
  validates :url, :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, :unless => Proc.new{self.url.blank?}

  attr_reader :author_tokens

  def author_tokens=(ids)
    if new_record?
      current_user = create_user_id
    else
      current_user = update_user_id
    end
    authors_ids = ids.split(",").map{|id|
      begin
        JournalCoAuthor.find(id).id
      rescue
        if id != "0"
          new_co_author = JournalCoAuthor.new(:co_author => id)
          new_co_author.save
          new_co_author.id
        else
          id
        end
      end
    }
    self.journal_co_author_ids = authors_ids
  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 save_writing_journal_files
    self.writing_journal_files.each do |t|
      if t.should_destroy
        t.destroy
      end
    end
  end

  def create_link
    title = []

    title << self.authors if self.authors.present?

    if !self.publication_date.nil?
      pd = self.publication_date.strftime("%Y-%m-%d").split('-')
      title << pd[0]
    end
    title << self.paper_title if self.paper_title.present?
    title << self.journal_title if self.journal_title.present?
    title << self.vol_no if (self.vol_no.present? && self.vol_no != "0")
    title << self.issue_no if (self.issue_no.present? && self.issue_no != "0")
    title << "pp"+self.form_to_start+"-"+self.form_to_end if (self.form_to_start.present? && self.form_to_start != "0")
    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.tagged_ids.delete('')
    self.journal_author_type_ids.delete('')
    self.journal_level_type_ids.delete('')
  end
end
