import moment from 'moment';
import { store } from '../store';
import { doLogOut, doSignIn } from '../actions/login';
import keycloak from '../config/sso/keycloak';
import ICAT from '../config/icat/icat';

export function getRemainingSessionTime(expirationTime) {
  return moment(expirationTime).diff(moment());
}

export function checkExpirationTime() {
  const { expirationTime } = store.getState().user;

  // If ICAT session is expired or expires in less than five minutes, log user out
  if (
    expirationTime &&
    getRemainingSessionTime(expirationTime) < 5 * 60 * 1000
  ) {
    store.dispatch(doLogOut({ expired: true }));
  }
}

export function matchAuthStateToSSO() {
  const { sessionId, isSSO } = store.getState().user;

  // If user is logged in to SSO but not to ICAT, log in to ICAT
  if (keycloak.authenticated && !sessionId) {
    store.dispatch(
      doSignIn(ICAT.authentication.sso.plugin, null, keycloak.idToken)
    );
    return;
  }

  // If user is logged in to ICAT but logged out of SSO, log out of ICAT
  // (Only log out users who had previously logged in through SSO)
  if (!keycloak.authenticated && sessionId && isSSO) {
    store.dispatch(doLogOut());
  }
}
