class Holiday < ApplicationRecord
  belongs_to :service_center

  # Ical download URL
  URL = "https://www.feiertage-oesterreich.at/content/kalender-download/force-download.php".freeze

  # Scopes
  scope :within_range, lambda { |range|
    where("date <= ? AND ? <= date", range.last, range.first)
  }
  scope :current_year_and_future, lambda {
    where("EXTRACT(year FROM date) >= ?", Time.current.year)
  }

  # Validations
  validates :name, :date, presence: true

  # Creates all national holidays from external source
  def self.import(years = (Time.current.year..Time.current.year + 1))
    require "icalendar"
    require "open-uri"

    # Download holidays and parse them using the icalendar gem
    events = URI.parse(URL).open do |file|
      Icalendar::Event.parse(file)
    end

    # Find or create holidays
    # Some holidays are yearly and some are different each year
    years.each do |year|
      select_events(year, events).map do |event|
        date = event.dtstart.change(year:)
        create_holiday(date, event)
      end
    end
  end

  def self.create_holiday(date, event)
    Holiday.find_or_create_by(service_center: ServiceCenter.first, date:) do |holiday|
      holiday.imported = true
      holiday.name = event.summary
    end
  end

  def self.select_events(year, events)
    events.select do |event|
      event.summary.include?("(§)") && (
        event.dtstart.year == year ||
        event.rrule&.first&.frequency == "YEARLY"
      )
    end
  end
end
