module Tools
  class IpResolverController < ApplicationController
    def show
      authorize IpResolver

      @resolved_items = {}
    end

    def resolve
      authorize IpResolver

      if params.key?(:resolve)
        resolve_audits && return
      end

      @resolved_items = {}

      if request.method_symbol != :get
        ips = IpComparison.ips_from_text(params[:ip_addresses])

        ips.each.with_index do |ip_address, index|
          begin
            ipgeo = IpComparison.geo_lookup_ip(ip_address)
          rescue IPAddr::InvalidAddressError => err
            flash[:error] = err
            render 'show'
            return nil
          end

          @resolved_items[index] = {
            addr: ip_address,
            geo: ipgeo
          }
        end
      end

      render 'show'
    end

    def resolve_audits
      authorize(History::QueryAudit, 'index?')

      options = params.fetch(:search, {})
      return if options.all? { |_k, v| v.blank? }

      options[:page] = params[:page]
      options.update(options) { |_k, v| v.downcase if v.is_a? String }

      audits = History::QueryAudit.all(options)

      # inject geoIP data into audit objects
      #  containing embedded IPs
      History::QueryAudit.hydrate_audits_geo!(audits)

      flash[:paging] = {
        total_pages: audits.total_pages,
        per_page: audits.per_page
      }

      @resolved_items = {}
      audits.each do |audit|
        next if audit.ip_geo.nil?
        @resolved_items[audit.uuid] = {
          audit: audit,
          addr: audit.ip,
          geo: audit.ip_geo
        }
      end

      @resolved_items = Service::Base.paginate(
        @resolved_items,
        per_page: audits.per_page,
        total_pages: audits.total_pages
      )

      render 'show'
    end

  end
end
