const omnis_calls = require('omnis_calls');
const {errorCodes, newErrorWithCode} = require('../errors.js');
try {
	var google = require("google-auth-library");
	var {JWT} = require("google-auth-library");
} catch (e) {
	throw newErrorWithCode(errorCodes.MISSING_DEPENDENCIES, "Could not load dependencies. Have you ran 'npm install' in 'jsworker/firebase_messaging'?");
}

let autoSendResponse = true; // Set to false in methods which should not send a response to Omnis when they exit. (e.g. async methods)


function getAccessToken(privateKeyPath) {
const SCOPES = ["https://www.googleapis.com/auth/firebase.messaging"];

  return new Promise(function(resolve, reject) {
    const key = require(privateKeyPath);
    const jwtClient = new JWT(
      key.client_email,
      null,
      key.private_key,
      SCOPES,
      null
    );
    jwtClient.authorize(function(err, tokens) {
      if (err) {
        reject(err);
        return;
      }
      resolve(tokens.access_token);
    });
  });
}


const methodMap = {

	getAccessToken: function(param, response) {
		autoSendResponse = false; // This method is asynchronous - we will manually send the response

		getAccessToken(param.keyPath).then((token) => {
			omnis_calls.sendResponse({"token": token}, response);
		})
		.catch((err) => {
			omnis_calls.sendError(response, 400, err.message);
		});

	}

}


module.exports = {
	call: function (method, param, response) { // The only requirement of an Omnis module is that it implement this function.

		autoSendResponse = true;

		if (methodMap[method]) {
			const result = methodMap[method](param, response);
			if (autoSendResponse)
				omnis_calls.sendResponse(result, response);
			return true;
		}
		else {
			throw newErrorWithCode(errorCodes.METHOD_NOT_FOUND, "");
		}

	}
};

