import { logger } from '/imports/utils/logger';

const DETAILED_GET_LOGS = false;

let counter = 0;

export class ApiEndpoint {
  constructor(appId, accessToken) {
    this.appId = appId;
    this.accessToken = accessToken;
    this.logGetDetails = DETAILED_GET_LOGS;
    this.correlationId = counter++;
  }

  debug(value = true) {
    this.logGetDetails = value;
    return this;
  }

  getRequestHeaders() {
    return {
      'X-HMIS-TrustedApp-Id': this.appId,
      Authorization: `HMISUserAuth session_token=${this.accessToken}`,
      Accept: 'application/json',
      'Content-Type': 'application/json',
    };
  }

  doGet(url) {
    const headers = this.getRequestHeaders();
    const options = { headers };
    logger.debug(`HMIS API:get#${this.correlationId} (${url})`, this.logGetDetails ? options : '');

    let response = false;
    try {
      response = HTTP.get(url, options);
    } catch (err) {
      this.throwApiError(url, headers, err, this.logGetDetails);
    }
    delete response.content;
    logger.debug(`HMIS API:get#${this.correlationId} res (${url})`,
      this.logGetDetails ? response : response.statusCode
    );
    return response.data;
  }

  doPost(url, data) {
    const options = {
      headers: this.getRequestHeaders(),
      data,
    };
    logger.debug(`HMIS API:post#${this.correlationId}`, { url, options });
    let response = false;
    try {
      response = HTTP.post(url, options);
    } catch (err) {
      this.throwApiError(url, options, err);
    }
    delete response.content;
    logger.debug(`HMIS API:post#${this.correlationId} res (${url})`, response);
    return response.data;
  }

  doPut(url, data) {
    const options = {
      headers: this.getRequestHeaders(),
      data,
    };
    logger.debug(`HMIS API:put#${this.correlationId}`, { url, options });
    let response = false;
    try {
      response = HTTP.put(url, options);
    } catch (err) {
      this.throwApiError(url, options, err);
    }
    delete response.content;
    logger.debug(`HMIS API:put#${this.correlationId} res (${url})`, response);
    return response.data;
  }

  doDel(url) {
    const options = {
      headers: this.getRequestHeaders(),
    };
    logger.debug(`HMIS API:del#${this.correlationId}`, { url, options });
    let response = false;
    try {
      response = HTTP.del(url, options);
    } catch (err) {
      this.throwApiError(url, options, err);
    }
    delete response.content;
    logger.debug(`HMIS API:del#${this.correlationId} res (${url})`, response);
    return response.data;
  }

  throwApiError(url, requestHeaders, httpError, logDetails = true) {
    if (logDetails) {
      logger.error('HMIS API', {
        url,
        requestHeaders,
        json_data: requestHeaders.data ? JSON.stringify(requestHeaders.data) : '',
        httpError,
      });
    } else {
      logger.error('HMIS API', {
        url,
        statusCode: httpError.response.statusCode,
      });
    }

    const code = httpError.response ? httpError.response.statusCode : 0;
    let message = '';
    try {
      const content = JSON.parse(httpError.response.content);
      if (_.isArray(content.error)) {
        message = content.error[0].message;
      } else {
        message = content.errors.error[0].message;
      }
    } catch (err) {
      message = httpError.message || 'An error has occurred';
    }
    throw new Meteor.Error('hmis.api', `${message} (${code})`, { code });
  }

}

@@ -931,24 +931,31 @@
 rowApiError(
+'get', 
 url, headers
@@ -1334,32 +1334,32 @@
 rrelationId%7D
-%60, %7B 
+ $%7B
 url
+%7D%60
 , options %7D)
@@ -1347,34 +1347,32 @@
 $%7Burl%7D%60, options
- %7D
 );%0A    let respo
@@ -1473,32 +1473,40 @@
 s.throwApiError(
+'post', 
 url, options, er
@@ -1806,32 +1806,34 @@
 rrelationId%7D
-%60, %7B url
+ ($%7Burl%7D)%60
 , options %7D)
@@ -1822,33 +1822,32 @@
 url%7D)%60, options 
-%7D
 );%0A    let respo
@@ -1947,32 +1947,39 @@
 s.throwApiError(
+'put', 
 url, options, er
@@ -2268,16 +2268,18 @@
 nId%7D
-%60, %7B url
+ ($%7Burl%7D)%60
 , op
@@ -2284,17 +2284,16 @@
 options 
-%7D
 );%0A    l
@@ -2405,24 +2405,31 @@
 rowApiError(
+'del', 
 url, options
@@ -2597,16 +2597,20 @@
 piError(
+op, 
 url, req
@@ -2691,33 +2691,33 @@
 ogger.error(
-'
+%60
 HMIS API
 ', %7B%0A       
@@ -2704,33 +2704,60 @@
 HMIS API
-', %7B%0A        url,
+:$%7Bop%7D#$%7Bthis.correlationId%7D res($%7Burl%7D)%60, %7B
 %0A       
@@ -2908,34 +2908,172 @@
     
-logger.error('HMIS API', %7B
+const code = httpError.response.statusCode;%0A      switch (code) %7B%0A        case 404:%0A          logger.warn(%60HMIS API:$%7Bop%7D#$%7Bthis.correlationId%7D res($%7Burl%7D)%60, code);
 %0A   
@@ -3077,20 +3077,24 @@
         
-url,
+  break;
 %0A       
@@ -3098,58 +3098,106 @@
     
-statusCode: httpError.response.statusCode,
+default:%0A          logger.error(%60HMIS API:$%7Bop%7D#$%7Bthis.correlationId%7D res($%7Burl%7D)%60, code);
 %0A      %7D
 );%0A 
@@ -3188,26 +3188,24 @@
 de);%0A      %7D
-);
 %0A    %7D%0A%0A    

improve api logging