class TimeCard::Entry < ApplicationRecord
  include Base::TimeCard::Entry

  attr_accessor :start_time, :stop_time

  belongs_to :school, foreign_key: :SchoolID, inverse_of: :time_card_entries
  belongs_to :classroom, foreign_key: :ClassID, optional: true, inverse_of: :time_card_entries
  belongs_to :employee, foreign_key: :UserID, inverse_of: :time_card_entries,
    class_name: '::Employee'
  belongs_to :task, foreign_key: :TCTID, class_name: '::TimeCard::Task', optional: true,
    inverse_of: :entries

  validates :date, :start, :stop, presence: true

  before_save :convert_start_and_stop_to_unix
  before_save :calculate_hours_and_minutes

  scope :by_date_range, ->(range) { where(date: range) if range.present? }
  scope :by_employee, ->(id) { where(employee_id: id) if id }

  private
    def convert_start_and_stop_to_unix
      self.start = start_time.to_datetime.to_i if start_time
      self.stop = stop_time.to_datetime.to_i if stop_time
    end

    def calculate_hours_and_minutes
      self.hours = (stop - start) / 3600
      self.minutes = (stop - start) / 60 % 60
    end
end
