import request from 'superagent'
import { ProxyAgent } from 'proxy-agent';

export default class DynatraceService {
  constructor(config) {
    this.request = request;
    if (process.env.http_proxy){
      this.proxy = new ProxyAgent();;
    } else {
      this.proxy = false;
    }
    this.config = config;
  }

  async getMetric(params) {
    let urlParams = "";
    params.forEach(param => {
      if (urlParams === ""){
        urlParams = "?" + param.key + "=" + encodeURIComponent(param.value);
      } else {
        urlParams += "&" + param.key + "=" + encodeURIComponent(param.value);
      }
    });
    const url = this.config.baseUrl + "/api/v2/metrics/query" + urlParams;

    try {
      let response = await this.request
      .get(url)
      .set("Authorization", "Api-Token " + this.config.token)
      .set("accept", "application/json; charset=utf-8")
      return response.body;
    } catch (error) {
        console.error('Error in dynatrace-service get: ' + error);
        return error;
    }
  }
}
