import jwt_decode from "jwt-decode";
import initialize from "./initialize";
import notifypoll from "./notifypoll";

export function processLogin(authResponse, loggedInWithKnownPassword) {
  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async function(resolve, reject) {
    try {
      //check there is a response of some kind
      if (!authResponse) {
        window.$gz.store.commit("logItem", "auth::processLogin -> no response");
        return reject();
      }

      //is token present?
      if (!authResponse || !authResponse.token) {
        window.$gz.store.commit(
          "logItem",
          "auth::processLogin -> response contains no data"
        );
        return reject();
      }
      const token = jwt_decode(authResponse.token);

      if (!token || !token.iss) {
        window.$gz.store.commit(
          "logItem",
          "auth::processLogin -> response token empty"
        );
        return reject();
      }

      if (token.iss != "rockfish.ayanova.com") {
        window.$gz.store.commit(
          "logItem",
          "auth::processLogin -> token invalid (iss): " + token.iss
        );
        return reject();
      }

      //ensure the store is clean first in case we didn't come here from a clean logout
      window.$gz.store.commit("logout");
      sessionStorage.clear(); //clear all temporary session storage data

      //encourage password changing if a purchased license
      if (loggedInWithKnownPassword)
        window.$gz.store.commit("setKnownPassword", true);

      //Put app relevant items into vuex store so app can use them
      window.$gz.store.commit("login", {
        apiToken: authResponse.token,
        authenticated: true,
        userId: Number(token.id),
        translationId: authResponse.tid,
        userName: authResponse.name,
        roles: authResponse.roles,
        userType: authResponse.usertype,
        dlt: authResponse.dlt,
        l: authResponse.l,
        tfaEnabled: authResponse.tfa,
        customerRights: authResponse.customerRights
      });

      //decided to remove this as it is not an out of the ordinary scenario to log
      // however left this block here in case in future becomes necessary for some common issue
      // //log the login
      // window.$gz.store.commit(
      //   "logItem",
      //   "auth::processLogin -> User " + token.id + " logged in"
      // );

      //Get global settings
      const gsets = await window.$gz.api.get("global-biz-setting/client");
      if (gsets.error) {
        //In a form this would trigger a bunch of validation or error display code but for here and now:
        //convert error to human readable string for display and popup a notification to user
        const msg = window.$gz.api.apiErrorToHumanString(gsets.error);
        window.$gz.eventBus.$emit("notify-error", msg);
      } else {
        //Check if overrides and use them here
        //or else use browser defaults
        window.$gz.store.commit("setGlobalSettings", gsets.data);
      }
      await initialize();
    } catch (err) {
      reject(err);
    }

    //start notification polling
    notifypoll.startPolling();
    resolve();
    //-------------------------------------------------
  });
}

export function processLogout() {
  notifypoll.stopPolling();
  window.$gz.store.commit("logout");
  sessionStorage.clear(); //clear all temporary session storage data
}

export function isLoggedIn() {
  return (
    !!window.$gz.store.state.apiToken &&
    !isTokenExpired(window.$gz.store.state.apiToken)
  );
}

function getTokenExpirationDate(encodedToken) {
  const token = jwt_decode(encodedToken);
  if (!token.exp) {
    return null;
  }

  const date = new Date(0);
  date.setUTCSeconds(token.exp);

  return date;
}

function isTokenExpired(token) {
  const expirationDate = getTokenExpirationDate(token);
  return expirationDate < new Date();
}
