class Branch < ApplicationRecord
  include RailsSettings::Extend

  belongs_to :institution
  has_many :expedients
  has_many :managements, through: :expedients

  scope :by_institution, -> (institution_id) { where(institution_id: institution_id) }

  default_scope { order(:name) }

  validates :name, presence: true

  def institution_name
    institution.try(:name)
  end

  # Business time config
  def set_business_config
    s = settings.get_all
    BusinessTime::Config.work_hours = work_hours(s)
    BusinessTime::Config.work_week = work_hours(s).keys
    holidays(s).each{|h| BusinessTime::Config.holidays << h }
  end

  def schedule_can_edit_closure
    self.update_column(:can_edit, false)
  end
  handle_asynchronously :schedule_can_edit_closure, :run_at => Proc.new { ENV['ADJUSTMENT_MINUTES_TIME'].to_i.minutes.from_now }

  private
    def work_hours(s)
      {
        :mon => s[:mon],
        :tue => s[:tue],
        :wed => s[:wed],
        :thu => s[:thu],
        :fri => s[:fri],
        :sat => s[:sat]
      }.reject { |k,v| v.all?(&:blank?) }
    end

    def holidays(s)
      s[:holidays].split(',').map{|d| Date.parse(d) rescue nil}.compact
    end
end
