class Attendance < ApplicationRecord
  include Base::Attendance

  associations_for legacy: true do |a|
    a.belongs_to :student
    a.belongs_to :school
    a.belongs_to :school_year
    a.belongs_to :classroom, keys: :ClassID
    a.belongs_to :type, keys: :ATID, optional: true
  end

  belongs_to :type_2, foreign_key: :ATID2, optional: true, class_name: 'Attendance::Type',
    inverse_of: :attendances

  associations_for namespace: 'EdFi' do |a|
    a.has_many :ids, as: :associated, inverse_of: :associated, dependent: :destroy
    a.has_many :logs, as: :associated, inverse_of: :associated
  end

  after_initialize :set_default_values, if: :new_record?

  before_validation :set_values

  validates :is_present, :absent, presence: true

  scope :order_by_class_name, -> { joins(:classroom).merge(Classroom.ordered) }
  scope :with_type_or_type_2, -> { where.not(type_id: 0).or(where.not(type_2_id: 0)) }
  scope :by_quarter, ->(quarter) { where(quarter: quarter) if quarter.present? }
  scope :by_classroom, ->(id) { where(class_id: id) if id.present? }
  scope :by_tardy, ->(tardy) { where(tardy: tardy, absent: 0) if tardy }
  scope :by_absent, ->(absent) { where.not(absent: 0) if absent }
  scope :by_parent_viewable, -> { joins(:classroom).merge(Classroom.by_parent_viewable(true)) }

  def self.timestamp_attributes_for_update
    super << 'DateTime'
  end

  private
    def set_default_values
      self.school = student.school
      self.school_year = school.school_years.current
      self.quarter = school_year.closest_quarter
    end

    def set_values
      self.homeroom = classroom.homeroom?

      self.is_present = tardy? if tardy_was.zero? && tardy?
      self.absent = !is_present?
      self.tardy = false if absent_was.zero? && absent?
    end
end
