module MerakiApi
  ENDPOINT = {
    create_network: "organizations/{organizationId}/networks",
    organizations: "organizations"
  }

  API_PATH_PREFIX = "/api/v1/"
  
  def self.get_API_url_endpoint
    "https://" + APPLICATION['defaults']['MERAKI']['HOSTNAME'] + API_PATH_PREFIX
  end

  def self.make_api_call(api_key, path, method, params={}, query_params={}) 
    url = URI(self.get_API_url_endpoint + path)
    url.query = URI.encode_www_form(query_params) if query_params.present?
    Rails.logger.info 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["X-Cisco-Meraki-API-Key"] = "#{api_key}"
      
      request.body = params.to_json
    elsif method == 'GET'
      puts "PATH:::::::::::::::#{path}"
 
      request = Net::HTTP::Get.new(url)
      request["X-Cisco-Meraki-API-Key"] = "#{api_key}"
    elsif method == 'PUT'
      request = Net::HTTP::Put.new(url)
      request["Content-Type"] = "application/json"
        p params.to_json
      request["X-Cisco-Meraki-API-Key"] = "#{api_key}"
      
      request.body = params.to_json
    elsif method == "DELETE"
      request = Net::HTTP::Delete.new(url)
      puts "delete method"
      request["X-Cisco-Meraki-API-Key"] = "#{api_key}"
    end
    response = https.request(request)
    Rails.logger.info "[MERAKI RESPONSE] :: [#{path}] :: --> #{response.read_body}"
    JSON.parse(response.read_body) rescue {}
  end

  def self.send_request(api_key, method, path, params={}, query_params={})

    url = URI(self.get_API_url_endpoint + path)
    url.query = URI.encode_www_form(query_params) if query_params.present?
    p 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["X-Cisco-Meraki-API-Key"] = "#{api_key}"
      
      request.body = params.to_json
    elsif method == 'GET'
      puts "PATH:::::::::::::::#{path}"

      request = Net::HTTP::Get.new(url)
      request["X-Cisco-Meraki-API-Key"] = "#{api_key}"
    elsif method == 'PUT'
      request = Net::HTTP::Put.new(url)
      request["Content-Type"] = "application/json"
        p params.to_json
      request["X-Cisco-Meraki-API-Key"] = "#{api_key}"
      
      request.body = params.to_json
    elsif method == "DELETE"
      puts "delete method"
    end
    response = https.request(request)
    Raisl.logger.info response.read_body
    JSON.parse(response.read_body) rescue {}
  end

  def self.make_api_call_old(api_key, endpoint_url, http_method, options_hash={})
    headers = {"X-Cisco-Meraki-API-Key" => api_key, 'Content-Type' => 'application/json'}

    options = {:headers => headers, :body => options_hash.to_json}
    case http_method
    when 'GET'
      res = HTTParty.get("#{self.get_API_url_endpoint}/#{endpoint_url}", options)
      raise "404 returned. Are you sure you are using the proper IDs?" if res.code == 404
      raise "Bad request due to the following error(s): #{JSON.parse(res.body)['errors']}" if res.body.include?('errors')
      return JSON.parse(res.body)
    when 'POST'
      res = HTTParty.post("#{self.get_API_url_endpoint}/#{endpoint_url}", options)
      Raisl.logger.info res
      raise "404 returned. Are you sure you are using the proper IDs?" if res.code == 404
      raise "Bad Request due to the following error(s): #{res['errors']}" if res['errors']
      begin
        return JSON.parse(res.body)
      rescue JSON::ParserError => e
        return res.code
      rescue TypeError => e
        return res.code
      end
    when 'PUT'
      res = HTTParty.put("#{self.get_API_url_endpoint}/#{endpoint_url}", options)
      # needs to check for is an array, because when you update a 3rd party VPN peer, it returns as an array
      # if you screw something up, it returns as a Hash, and will hit the normal if res['errors'
      Raisl.logger.info res
      raise "404 returned. Are you sure you are using the proper IDs?" if res.code == 404
      (raise "Bad Request due to the following error(s): #{res['errors']}" if res['errors']) unless JSON.parse(res.body).is_a? Array
      return JSON.parse(res.body)
    when 'DELETE'
      res = HTTParty.delete("#{self.get_API_url_endpoint}/#{endpoint_url}", options)
      Raisl.logger.info res
      raise "404 returned. Are you sure you are using the proper IDs?" if res.code == 404
      raise "Bad Request due to the following error(s): #{res['errors']}" if res['errors']
      return res
    else
      raise 'Invalid HTTP Method. Only GET, POST, PUT and DELETE are supported.'
    end
  end
end