# frozen_string_literal: true require 'holiday' require 'active_support' require 'active_support/core_ext' class WorkDay include Singleton attr_accessor :calendars def self.calendars(calendars) instance.calendars = calendars end def work_day?(date) date = date.try(:to_date) return unless date ![0, 6].include?(date.wday) && !holidays_in(date.year).include?(date) end def last_until(date, days = 0) date = date.try(:to_date) return unless date date -= 1 until work_day?(date) days -= 1 days == -1 ? date : last_until(1.day.ago(date), days) end def next_after(date, days = 1) date = date.try(:to_date) day_counter = 0 while day_counter < days date += 1 day_counter += 1 if work_day?(date) end work_day?(date) ? date : next_after(date) end def between(start_date, end_date) (start_date.to_date..end_date.to_date).select { |date| work_day?(date) } end def self.work_day?(date) WorkDay.instance.work_day?(date) end def self.last_until(date, days = 0) WorkDay.instance.last_until(date, days) end def self.next_after(date, days = 1) WorkDay.instance.next_after(date, days) end def self.between(start_date, end_date) WorkDay.instance.between(start_date, end_date) end private def holidays_in(year) @calendars ||= ['brazil'] @holidays ||= {} @holidays[calendars] ||= {} @holidays[calendars][year] ||= Holiday.new(calendars).in(year) end end