module LatencyHelper
  
  #GOOD = <40ms, FAIR = 40-60ms, and POOR = >60ms

  LATENCY_SCORES = {
    good: { label: 'GOOD', min: 0, max: 40 },
    fair: { label: 'FAIR', min: 40, max: 60 },
    high: { label: 'HIGH', min: 60, max: 10000000 },
    me: { label: 'ME', min: -1, max: -1 },
    unknown: { label: 'UNKNOWN', min: -2, max: -2 }
  };

  def users_latency_data(latency_good, latency_fair, latency_high, filter_opts, offset, limit)

    latency_data = []
   
    uri = URI(filter_latency_url)
    begin
      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = true if Rails.application.config.latency_data_host.start_with?("https://")
      req = Net::HTTP::Post.new(uri)
      req["Authorization"] = "Basic #{Rails.application.config.latency_data_host_auth_code}"
      req["Content-Type"] = "application/json"

      req_params = {
        my_user_id: current_user.id,
        my_public_ip: request.remote_ip,
        my_device_id: nil,
        my_client_id: nil,
        from_location: filter_opts[:from_location] || "0",
        offset: offset,
        limit: limit
      }

      req_params.merge!(instruments: filter_opts[:instruments]) if filter_opts[:instruments]
      req_params.merge!(genres: filter_opts[:genres]) if filter_opts[:genres]
      req_params.merge!(joined_within_days: filter_opts[:joined_within_days]) if filter_opts[:joined_within_days]
      req_params.merge!(active_within_days: filter_opts[:active_within_days]) if filter_opts[:active_within_days]

      req.body = req_params.to_json

      response = http.request(req)

      #debugger
      
      if response.is_a?(Net::HTTPOK) || response.is_a?(Net::HTTPSuccess)
        json_body = JSON.parse(response.body)
        graph_db_users = json_body['users']
        nextOffset     = json_body['next']

        if latency_good || latency_fair || latency_high
          #fiter by latency params
          graph_db_users.select! do |user|
            total_latency = user["ars"]["total_latency"].to_f
            (total_latency >= LATENCY_SCORES[:good][:min] && total_latency <= LATENCY_SCORES[:good][:max] && latency_good) ||
            (total_latency > LATENCY_SCORES[:fair][:min] && total_latency <= LATENCY_SCORES[:fair][:max] && latency_fair) ||
            (total_latency > LATENCY_SCORES[:high][:min] && latency_high)
            end
        end

        latency_data = graph_db_users.map { | user |
          { 
            user_id: user["user_id"],
            audio_latency: user["audio_latency"].to_f,
            ars_total_latency: user["ars"]["total_latency"].to_f,
            ars_internet_latency: user["ars"]["internet_latency"].to_f
          }
        }.uniq
        
        return {data: latency_data, next: nextOffset} 
      else
        logger.debug("Latency response failed: #{response}")
        Bugsnag.notify("LatencyResponseFailed") do |report|
          report.severity = "faliure"
          report.add_tab(:latency, {
            user_id: current_user.id,
            name: current_user.name,
            params: params,
            url: filter_latency_url,
            code: response.code,
            body: response.body,
          })
        end
      end
    rescue => exception
      raise exception
    end
   
  end

end