class SchoolDecorator < ApplicationDecorator
  delegate :name, :alpha2, to: :country, prefix: true, allow_nil: true

  def payment_options
    [].tap do |options|
      options << { label: 'Cash', type: :cash }
      options << { label: 'Check (paper)', type: :check }
      options << { label: 'Check (ACH)', type: :payjunction_ach } if open?(:ach)
      options << { label: 'Credit Card', type: :payjunction_credit_card } if open?(:credit_card)
      options << { label: 'Credit Card', type: :paya_credit_card } if paya_config&.enabled
    end
  end

  def payment_methods
    payment_options.map { |o| o[:type] }
  end

  def address_line
    "#{address}, #{city}, #{state} #{zip}"
  end

  def school_documents(human_size=false)
    size = Dir.glob(dir_path.join('0', 'Docs', '**', '*')).map { |f| File.size(f) }.sum
    return size unless human_size

    h.number_to_human_size(size)
  end

  def school_photos(human_size=false)
    size = Dir.glob(dir_path.join('0', 'Photos', '**', '*')).map { |f| File.size(f) }.sum
    return size unless human_size

    h.number_to_human_size(size)
  end

  def class_documents(human_size=false)
    file_size(sub_dir: 'Docs', human_size: human_size)
  end

  def class_photos(human_size=false)
    file_size(sub_dir: 'Photos', human_size: human_size)
  end

  def student_profile_documents(human_size=false)
    file_size(area: 'Students', human_size: human_size)
  end

  def employee_profile_documents(human_size=false)
    file_size(area: 'Employees', human_size: human_size)
  end

  def user_documents(human_size=false)
    file_size(area: 'Users', human_size: human_size)
  end

  private
    def open?(type)
      case type
      when :ach
        payjunction_accounts.ach.open.present?
      when :credit_card
        payjunction_accounts.credit_card.open.present?
      end
    end

    def file_size(area: '', sub_dir: '', human_size: false)
      path = dir_path.join(area)
      size = Dir.glob(path.join('*')).map do |file_path|
        next unless File.directory?(file_path)
        next if (dir_id = File.basename(file_path).split('/').last).to_i.zero?

        Dir.glob(path.join(dir_id, sub_dir, '**', '*')).map { |f| File.size(f) }
      end.compact.flatten.sum
      return size unless human_size

      h.number_to_human_size(size)
    end
end
