class ClassAssignment < Base::ClassAssignment
  enum status: { current: 1, graded: 2, future: 3 }

  belongs_to :classroom, foreign_key: :ClassID
  belongs_to :class_subject, foreign_key: :ClassSubjectID, optional: true
  belongs_to :class_grade_category, foreign_key: :CGCID, optional: true
  belongs_to :class_assignment_group, foreign_key: :CAGID, optional: true

  has_many :class_grades, foreign_key: :CAID
  has_many :class_assignment_attachments, foreign_key: :CAID
  has_many :documents, through: :class_assignment_attachments

  delegate :school, to: :classroom
  delegate :school_config, to: :school

  after_initialize :set_school, if: :new_record?

  validates :name, :quarter, :due_date, :status, presence: true

  scope :exclude_future, -> { where.not(status: :future) }
  scope :by_status, ->(status) { where(status: status) if status }
  scope :by_subject, ->(subject_id) { where(class_subject_id: subject_id) if subject_id.present? }
  scope :by_quarter, ->(quarter) { where(quarter: quarter) if quarter }
  scope :by_classroom, ->(class_id) { where(class_id: class_id) if class_id }
  scope :by_parent_viewable, -> { joins(:classroom).merge(Classroom.by_parent_viewable(true)) }
  scope :with_viewable_grades, -> { joins(:classroom).merge(Classroom.with_viewable_grades) }
  scope :by_due_date, ->(date) { where(due_date: date) if date }


  scope :by_grade_status, ->(grade_status, student=nil) do
    return unless grade_status

    joins(:class_grades).by_grade_student(student).merge(ClassGrade.by_status(grade_status))
  end

  scope :without_grade_status, ->(grade_status, student=nil) do
    return unless grade_status

    joins(:class_grades).by_grade_student(student).merge(ClassGrade.without_status(grade_status))
  end

  scope :by_grade_student, ->(student) do
    joins(:class_grades).merge(ClassGrade.by_student(student)) if student
  end

  def semester=(val)
    @semester = val
    self.quarter = school_config.semesters? && val == 2 ? 3 : val
  end

  def semester
    self.semester = if school_config.sessions? || school_config.trimesters?
      quarter
    elsif [1, 2].include?(quarter)
      1
    else
      2
    end
  end

  private
    def set_school
      self.school_id = classroom.school_id
    end
end
