const axios = require('axios');
const EventSource = require('eventsource');

async function getProgressKey(prefix) {
  prefix = prefix ? prefix : 'txttosl-api-node';

  return (await axios.get(`https://api.txttosl.com/api/v1/progress/key?prefix=${prefix}`)).data;
}

async function translate(text, lang, options, progressCallback, progressKeyPrefix) {
  if (options === undefined) {
    options = {};
  }

  if (!('redirect' in options)) {
    options.redirect = false;
  }

  var progressKey = undefined;
  if (progressCallback) {
    progressKey = await getProgressKey(progressKeyPrefix);

    if (!('progressKey' in options)) {
      options.progressKey = progressKey;
    }
  }

  var arguments = {
    lang: lang,
    text: text,
    ...options
  };

  var requestArguments = Object.entries(arguments).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join('&');

  var requestPromise = axios.get('https://api.txttosl.com/api/v1/translate', {
    params: arguments
  });

  if (progressKey) {
    var progressStream = new EventSource(`https://api.txttosl.com/api/v1/progress/stream?progressKey=${progressKey}`);

    progressStream.onmessage = function(event) {
      progressCallback(event.data);
    };
  }

  return (await requestPromise).data;
}

module.exports = {
  translate,
  getProgressKey
};
