/* xeslint-disable */
import decode from "jwt-decode";
import store from "../store";
import initialize from "./initialize";

export function processLogin(response) {
  //is token present?
  if (!response || !response.data || !response.data.token) {
    store.commit("logItem", "auth::processLogin -> response empty");
    return Promise.reject();
  }
  const token = decode(response.data.token);

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

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

  //Put app relevant items into vuex store so app can use them
  store.commit("login", {
    apiToken: response.data.token,
    authenticated: true,
    userId: Number(token.id),
    roles: token["ayanova/roles"]
  });

  //Initialize the application
  initialize();
  store.commit(
    "logItem",
    "auth::processLogin -> User " + token.id + " logged in"
  );
  return Promise.resolve(true);
}

export function processLogout() {
  if (store.state.authenticated) {
    store.commit("logItem", "auth::processLogout -> User logged out");
  }
  store.commit("logout");
}

export function isLoggedIn() {
  //const token = getToken();
  return !!store.state.apiToken && !isTokenExpired(store.state.apiToken);
}

function getTokenExpirationDate(encodedToken) {
  const token = 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();
}
