module WrapperApi
  require 'fileutils'
  require 'tempfile'

  def self.send_oauth_request(method, path, params={}, query_params={})
    url = URI(path)
    url.query = URI.encode_www_form(query_params) if query_params.present?

    Rails.logger.info "[OPENWIFI] Request URL :: #{url}"
    https = Net::HTTP.new(url.host, url.port)
    https.use_ssl = true
    https.verify_mode = OpenSSL::SSL::VERIFY_NONE
    
    if method == 'POST'
      request = Net::HTTP::Post.new(url)
      request["Content-Type"] = "application/json"
      request.body = params.to_json
    end
    response = https.request(request)
    
    JSON.parse(response.read_body) rescue {}  
  end

  def self.send_request(int_type, method, path, params={}, query_params={})
    openwifi_token = $redis.hgetall (int_type.present? ? "OPENWIFI:SDK:USER:#{int_type.id}" : 'OPENWIFI:SDK:USER')
    #REFRESH TOKEN if it expires. default expiry: 30days on SDK
    access_token = openwifi_token['access_token']
    if access_token.blank? || (openwifi_token['created_at'].present? && openwifi_token['expires_in'].present? && (Time.now - 1.day).to_i > (openwifi_token['created_at'].to_i + openwifi_token['expires_in'].to_i))
      Rails.logger.info "[OPENWIFI][ACCESS TOKEN (#{access_token.present?}) RESET] :: INT TYPE (#{int_type})"
      res = OpenWifi::SecurityService.new(int_type).oauth2
      access_token = $redis.hget (int_type.present? ? "OPENWIFI:SDK:USER:#{int_type.id}" : 'OPENWIFI:SDK:USER'), "access_token"
    end
    url = URI(path)
    url.query = URI.encode_www_form(query_params) if query_params.present?
    Rails.logger.info "[OPENWIFI] Request URL :: #{url}"
    https = Net::HTTP.new(url.host, url.port)
    https.use_ssl = true
    https.verify_mode = OpenSSL::SSL::VERIFY_NONE
    

    if method == 'POST'
      request = Net::HTTP::Post.new(url)
      request["Content-Type"] = "application/json"
      request["Authorization"] = "Bearer #{access_token}"
      
      request.body = params.to_json
    elsif method == 'GET'
      puts "PATH:::::::::::::::#{path}"

      request = Net::HTTP::Get.new(url)
      request["Authorization"] = "Bearer #{access_token}"
    elsif method == 'GET-FILE'
      puts "PATH:::::::::::::::#{path}"

      request = Net::HTTP::Get.new(url)
      request["Content-Type"] = "pcap"
      request["Authorization"] = "Bearer #{access_token}"
    elsif method == 'PUT'      
      request = Net::HTTP::Put.new(url)
      request["Content-Type"] = "application/json"
        p params.to_json
      request["Authorization"] = "Bearer #{access_token}"
      
      request.body = params.to_json
    elsif method == "DELETE"
      puts "delete method"
    end
    response = https.request(request)
    if method == "GET-FILE"
      res = response.read_body
      return res
    end
    JSON.parse(response.read_body) rescue {}
  end
end
