require 'open-uri'
require 'uri'
require './core/network_traffic_analytics/schema_validator'

# filtering.rb will filter HAR events
class Filtering
  include RSpec::Matchers

  # Legacy values required to be backward compatible during the transition to new hostnames
  SPADE_LEGACY = ["spade.twitch.tv", "trowel.twitch.tv", "video-edge-8a9219.sjc01.hls.ttvnw.net"]

  # File with the [last, current, next] valid Spade hostnames.
  SPADE_FILE_URL = 'https://s3-us-west-2.amazonaws.com/science-output/spade-window'

  def initialize(proxy)
    @proxy = proxy
  end

  def get_json_har
    return JSON.parse(@proxy.get_har_data)
  end

  def valid_spade_url?(url)
    host = URI.parse(url).host
    if SPADE_LEGACY.include? host
      return true
    end
    begin
      retries ||= 0
      json_list = JSON.parse(open(SPADE_FILE_URL, :read_timeout => 5).read)
    rescue
      retry if (retries += 1) < 3
    end
    json_list.each do |item|
      if host == item["name"]
        return true
      end
    end
    return false
  end

  # Method to filter the HAR file for urls
  # containing SPADE POST DATA. Once filtered, the POST DATA
  # is Base64 decoded, JSON-ified, and stored into an array.
  # @param response [Hash] The response contains HAR data.
  # @return @@spade_events [Array] A collection of all entry bodies matching @@spade_url.
  def filter_spade_events
    network_traffic = get_json_har
    length = network_traffic['log']['entries'].length.to_i
    index = 0
    spade_events = Array.new

    while index < length do
      if valid_spade_url?(network_traffic['log']['entries'][index]['request']['url'])

        param_value = network_traffic['log']['entries'][index]['request']['postData']['params'][0]['value']
        # puts "param_value: #{param_value}"
        decoded_param_value = Base64.decode64(param_value)
        json_param_value = JSON.parse(decoded_param_value)
        if json_param_value.class == Hash
          event_name = json_param_value['event']
          event_body = json_param_value
          spade_events << [event_name, event_body]
        elsif json_param_value.class == Array
          json_param_value.each do |event|
            spade_events << [event['event'], event]
          end
        end
      end
      index += 1
    end
    return spade_events
  end
end
