'use strict';

// LOCALS
const tools = require('./tools');
const configUtils = require('../csdr/config/config-utils');

// FETCH ARGS
const { apiUserId, apiPassword } = tools.getArgs();

// PRIVATES
let authToken;


const handleResponse = (response) => {
  tools.logDebug(JSON.stringify(response));

  if (response.ok) {
    return response.data;
  } else {
    throw new Error(response.message);
  }
}

module.exports.login = () => {
  const fetch = require('node-fetch');
  const { API_HOST } = configUtils.global.getConfigOptions();

  tools.logInfo(`API Login - userId:${apiUserId}`);

  return Promise.resolve()
    .then(() => {
      return fetch(`${API_HOST}/auth`, {
        method: 'post',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({
            "userid": apiUserId,
            "password": apiPassword
        })
      })
    })
    .then((res) => {
      tools.logDebugResponse(res);
      return res.json();
    })
    .then((response) => {
      authToken = response.token;
      return handleResponse(response);
    })
    .catch(e => {
      tools.logDebugTrace(__filename, 'login', e);
      throw e;
    });
}


module.exports.get = (pathName) => {
  const fetch = require('node-fetch');
  const { API_HOST } = configUtils.global.getConfigOptions();

  tools.logInfo(`API get - pathName: ${pathName}`);

  return Promise.resolve()
    .then(() => {
      if (!authToken) {
        return this.login();
      }
    })
    .then(() => {
      return fetch(`${API_HOST}${pathName}`, {
        method: 'get',
        headers: {
          'content-type': 'application/json',
          'x-auth-token': authToken
        },
      })
    })
    .then((res) => {
      tools.logDebugResponse(res);
      return res.json();
    })
    .then((response) => {
      return handleResponse(response);
    })
    .catch(e => {
      tools.logDebugTrace(__filename, 'get', e);
      throw e;
    });
}


module.exports.authPost = (pathName, body) => {
  const fetch = require('node-fetch');
  const { API_HOST } = configUtils.global.getConfigOptions();

  tools.logInfo(`API post - pathName: ${pathName} - body: ${JSON.stringify(body)}`);

  return Promise.resolve()
    .then(() => {
      if (!authToken) {
        return this.login();
      }
    })
    .then(() => {
      return fetch(`${API_HOST}${pathName}`, {
        method: 'post',
        headers: {
          'content-type': 'application/json',
          'x-auth-token': authToken
        },
        body: JSON.stringify(body)
      })
    })
    .then((res) => {
      tools.logDebugResponse(res);
      return res.json();
    })
    .then((response) => {
      return handleResponse(response);
    })
    .catch(e => {
      tools.logDebugTrace(__filename, 'post', e);
      throw e;
    });
}


module.exports.post = (host, pathName, body) => {
  const fetch = require('node-fetch');

  tools.logInfo(`API post - host: ${host}`);

  return Promise.resolve()
    .then(() => {
      return fetch(`${host}${pathName}`, {
        method: 'POST',
        headers: {
          'content-type': 'application/json'
        },
        body: JSON.stringify(body)
      })
    })
    .then((res) => {
      handleResponse(res);
      return res.json();
    })
    .catch(e => {
      tools.logDebugTrace(__filename, 'post', e);
      throw e;
    });
}


