namespace :gear do

  task analyze: :environment do

    successful = {types: {}}

    Diagnostic.where("type = 'GEAR_SELECTION'").each do |diagnostic|

      data = JSON.parse(diagnostic.data)

      os = data["summary"]["os"] # MacOSX or Win32
      success = data["summary"]["success"] # bool

      if success
        latency = data["summary"]["score"]["latencyScore"]["latency"]
        id = data["summary"]["selectedDevice"]["input"]["info"]["id"]
        displayName = data["summary"]["selectedDevice"]["input"]["info"]["displayName"]
        type = data["summary"]["selectedDevice"]["input"]["info"]["type"]

        store = successful[:types][type]

        if !store
          store = {}
          successful[:types][type] = store
        end

        deviceData = store[id + ':' + latency.to_i.to_s]

        if !deviceData
          deviceData = {id: id, displayName: displayName, type: type, latency: latency, count: 0}
          store[id + ':' + latency.to_i.to_s] = deviceData
        end

        deviceData[:count] = deviceData[:count] + 1
      end
    end

    puts "TYPES:"
    successful[:types].each do|type, hits|
      puts "#{type}"
    end
    puts ""
    puts ""
    
    successful[:types].each do |type, hits|
      results = hits.sort_by do |id_latency, deviceData|
        deviceData[:latency]
      end

      puts "--------------- #{type} -----------------"

      results.each do |result|
        puts "#{result[1][:latency].to_i.to_s.rjust(2)}  #{result[1][:displayName]}"
      end
      puts ""
      puts ""
    end
  end
end
