# encoding: utf-8
class Syllabus < ActiveRecord::Base
  include Redmine::SafeAttributes
  include ApplicationHelper
  acts_as_taggable
  acts_as_attachable
  has_many_kindeditor_assets :assets, :dependent => :destroy

  belongs_to :user
  has_many :courses
  has_many :journals_for_messages, :as => :jour, :dependent => :destroy
  has_many :syllabus_members, :dependent => :destroy
  has_many :praise_tread, as: :praise_tread_object, dependent: :destroy
  has_one :praise_tread_cache, as: :object, dependent: :destroy
  attr_accessible :description, :user_id, :title, :eng_name, :syllabus_type, :credit, :hours, :theory_hours, :practice_hours, :applicable_major, :pre_course
  safe_attributes 'title','user', 'description', 'eng_name', 'syllabus_type', 'credit', 'hours', 'theory_hours', 'practice_hours', 'credit', 'applicable_major', 'pre_course'

  validates :title, :user_id, presence: true

  scope :like, lambda {|arg|
    if arg.blank?
      where(nil)
    else
      pattern = "%#{arg.to_s.strip.downcase}%"
      where(" LOWER(title) LIKE :p ", :p => pattern)
    end
  }

  def delete_kindeditor_assets
    delete_kindeditor_assets_from_disk self.id,OwnerTypeHelper::SYLLABUS
  end

  def syllabus_type_str
    case self.syllabus_type
      when 1
        type = "公共必修课"
      when 2
        type = "学科必修课"
      when 3
        type = "专业选修课"
      when 4
        type = "实践必修课"
      when 5
        type = "实践选修课"
    end
    type
  end

  ###添加回复
  def self.add_syllabus_jour(user, notes, id , options = {})
    syllabus = Syllabus.find(id)
    if options.count == 0
      jfm = syllabus.journals_for_messages.build(:user_id => user.id, :notes => notes, :reply_id => 0)
    else
      jfm = syllabus.journals_for_messages.build(options)
    end
    jfm.save
    jfm
  end
end
