var BASE_URL = 'https://plus-app.ucsc.eu/public';
var SERVICE_HANDSHAKE = 'https://plus.ucsc.eu/api';
var DEPLOYED_VERSION_URL =
  'https://plus-app.ucsc.eu/desktop-version.json';

import version_json from '../package.json' with { type: 'json' };

var checkVersion = function (currentVersion, latestVersion) {
  var updateRequired = false
  var latestSplitted = latestVersion.split('.')
  var currentSplitted = currentVersion.split('.')

  var latestSize = latestSplitted.length
  for (var i = 0; i < latestSize; i++) {
    if (!currentSplitted[i]) {
      currentSplitted[i] = '0'
    }
    var current = Number(currentSplitted[i])
    var latest = Number(latestSplitted[i])
    if (latest > current) {
      updateRequired = true
      break
    } else if (current > latest) {
      break
    }
  }
  return updateRequired
}

var init = function (scope) {
  scope
    .fetch(SERVICE_HANDSHAKE)
    .then(async function () {
      var response = await fetch(DEPLOYED_VERSION_URL);
      var response_json = await response.json();
      if (checkVersion(version_json.version, response_json.version)) {
        document.getElementById('loader').style.display = 'none';
        document.getElementById('new-update-found').style.display = 'block';
      } else {
        scope.location = BASE_URL + '?t=' + Date.now();
      }
    })
    .catch(function (e) {
      document.getElementById('loader').style.display = 'none';
      document.getElementById('error').style.display = 'block';
    });
};

init(window);
