class SchoolDay < ApplicationRecord
  include Base::SchoolDay

  associations_for legacy: true do |a|
    a.belongs_to :school
    a.belongs_to :school_year
  end

  belongs_to :school_year_session, ->(record) { where(sequence: record.quarter) },
    foreign_key: :SchoolYearID, primary_key: :SchoolYearID, optional: true

  associations_for namespace: 'Covid' do |a|
    a.has_many :screenings
  end

  associations_for namespace: 'EdFi' do |a|
    a.has_many :logs, as: :associated, inverse_of: :associated

    a.has_one :id, as: :associated, inverse_of: :associated, dependent: :destroy
  end

  belongs_to :day_descriptor, class_name: 'EdFi::Descriptor', optional: true

  before_validation :set_school, unless: :school_id?

  before_save :round_hours

  validates :date, presence: true, uniqueness: { scope: :school }
  validates :quarter, :half_day, presence: true
  validates :hours, numericality: { greater_than_or_equal_to: 0 }

  validate :date_within_academic_year, if: :date

  scope :with_date_range, ->(range) { where(date: range) if range.present? }
  scope :by_quarter, ->(quarter) { where(quarter: quarter) if quarter }
  scope :by_half_day, ->(flag) { where(half_day: flag) unless flag.nil? }
  scope :by_cycle_day, ->(day) { where(cycle_day: day) if day }
  scope :ordered, ->(order=:asc) { order(date: order) }

  scope :by_semester, ->(semester, year) do
    return unless semester || year

    range = case semester
    when :semester_1
      [year.q1_start..year.q3_start - 1]
    when :semester_2
      [year.q3_start..year.end]
    end

    where(date: range)
  end

  def delete_edfi_record
    EdFi::Indiana::Sandbox::CalendarDatesService.new(school_year_id, { id: ed_fi_id }).delete
  end

  private
    def round_hours
      self.hours = (hours * 4).round / 4.0
    end

    def set_school
      self.school_id = school_year.school_id
    end

    def date_within_academic_year
      return if [school_year.academic_year, school_year.academic_year - 1].include?(date.year)

      errors.add(:date, 'enter a date within the academic year')
    end
end
