class Institution < ApplicationRecord
  include RailsSettings::Extend

  has_and_belongs_to_many :users
  has_many :branches, dependent: :destroy
  has_many :expedients, dependent: :destroy

  default_scope { order(acts_as_label) }
  scope :visible,            -> { where(visible: true) }

  has_attached_file :avatar, styles: { profile: '150x150>' }
  validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\z/

  after_create :prepare_extra_data

  ransacker :name, type: :string do
    Arel.sql("UNACCENT(\"#{table_name}\".\"name\")")
  end

  def self.acts_as_label
    :name
  end

  def acts_as_label
    send(self.class.acts_as_label)
  end

  def statistic_by_type?
    self.statistic_by_type == {} ? true : false
  end

  def statistic_by_type
    r = self.expedients.group(:state).count.each_with_object({}) do |v, hash|
      hash[Expedient::STATE[v[0]].to_s] = v[1]
    end
    r
  end

  def statistic_by_kind?
    r=0
    k = self.statistic_by_kind
    k.each{|s| s[1] == 0 ? r += 1 : nil}
    r == k.length ? true : false
  end

  def statistic_by_kind
    Management.pluck(:kind).uniq.each_with_object({}) do |v, hash|
      hash[Management::KIND[v].to_s] = Management.where(expedient_id: self.expedients.ids, kind: v).count
    end
  end

  def statistic_contact_time?
    r=0
    t = self.statistic_contact_time
    t.each{|s| s[1] == 0 ? r += 1 : nil}
    r == t.length ? true : false
  end

  def statistic_contact_time
    e = self.expedients
    less_48hours     = e.where("contact_business_days <= 2").count
    more_48hours     = e.where("contact_business_days > 2").count
    wo_contact       = e.where(anonymous: true).count
    failed_contact   = e.joins(:events).where("expedients.contact_business_days IS NULL").where("events.state = 'failed_communication_attempt'").distinct.count

    [
      ["Menos de 48 horas", less_48hours],
      ["Más de 48 horas", more_48hours],
      ["Contacto fallido", failed_contact],
      ["Sin contacto", wo_contact]
    ]
  end

  def self.times
    h = []
    start_time = Time.now.beginning_of_day + 6.hours
    end_time = start_time + 12.hours
    while start_time <= end_time
      h << start_time.strftime('%H:%M')
      start_time += 30.minutes
    end
    return h
  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 prepare_extra_data
      # create the entry ways
      begin
        Config['entry_ways']['institution'].each do |k, v|
          EntryWay.where(institution_id: self.id, name: k, classification: v).first_or_create
        end
      rescue
      end
      # create the management categories
      begin
        Config['management_categories'].each do |k, values|
          values.each do |v|
            ManagementCategory.where(institution_id: self.id, kind: k, name: v).first_or_create
          end
        end
      rescue
      end
    end

    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
