# frozen_string_literal: true
#
namespace :default do

  desc 'Load default entry ways'
  task entry_ways: :environment do
    Config['entry_ways']['general'].each do |k, v|
      EntryWay.where(name: k, classification: v).first_or_create
    end
  end

  desc 'Load contact time days/hours and management deadlines'
  task load_deadlines: :environment do
    # Management.includes(expedient: :institution).where('deadline_at is null or closed_business_days is null').each do |m|
    Management.includes(expedient: :institution).each do |m|
      institution = m.expedient.try(:institution)
      if institution
        institution.set_business_config
        response_days = institution.settings.response_days.to_i
        m.update_column(:deadline_at, response_days.business_days.after(m.created_at)) if m.deadline_at.nil?
        if m.closed?
          start_date = m.created_at
          end_date = m.closed_at
          m.update_column(:closed_business_days, start_date.to_date.business_days_until(end_date.to_date))
          m.update_column(:closed_business_hours, start_date.business_time_until(end_date).to_f/60/60)
        end
      end
    end
    Expedient.update_all(contact_business_days: nil, contact_business_hours: nil, closed_business_days: nil, closed_business_hours: nil)
    Expedient.includes(:institution).each do |exp|
      institution = exp.institution
      institution.set_business_config
      start_at = exp.received_at
      contact_at = exp.events.where(state: 'process').first.try(:start_at)
      closed_at = exp.closed_at
      if contact_at
        exp.update_column(:contact_business_days, start_at.to_date.business_days_until(contact_at.to_date))
        exp.update_column(:contact_business_hours, start_at.business_time_until(contact_at).to_f/60/60)
      end
      if closed_at
        exp.update_column(:closed_business_days, start_at.to_date.business_days_until(closed_at.to_date))
        exp.update_column(:closed_business_hours, start_at.business_time_until(closed_at).to_f/60/60)
      end
    end
  end

end
