"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createTokenBundle = void 0;

var _reduxBundler = require("redux-bundler");

var _tokenWriter = require("../utils/token-writer");

const UPDATED = 'TOKEN_UPDATED';
const CLEARED = 'TOKEN_CLEARED';
const cookieReadInterval = 10000;

const getTokenFromHash = () => location.hash.split('token=')[1] || null;

const createTokenBundle = opts => {
  const {
    readToken,
    writeToken,
    clearToken
  } = (0, _tokenWriter.createTokenWriter)(opts);
  return {
    name: 'token',
    getReducer: () => {
      let token = readToken();

      if (token === 'null') {
        token = null;
      }

      if (!token) {
        const fromHash = getTokenFromHash();

        if (fromHash) {
          token = fromHash;
          writeToken(token);
        }
      }

      const initial = {
        token
      };
      return (state = initial, {
        type,
        payload
      }) => {
        if (type === UPDATED) {
          return Object.assign({}, state, {
            token: payload
          });
        }

        if (type === CLEARED) {
          return Object.assign({}, state, {
            token: null
          });
        }

        return state;
      };
    },
    init: store => {
      if (_reduxBundler.IS_BROWSER) {
        const read = () => {
          store.doUpdateTokenFromCookie();
          setTimeout(() => (0, _reduxBundler.ric)(read), cookieReadInterval);
        };

        setTimeout(read, cookieReadInterval);
      }
    },
    selectAuthToken: state => state.token.token,
    selectHasAuthToken: state => !!state.token.token,
    doReceiveToken: token => ({
      dispatch,
      store
    }) => {
      if (token === 'null' || !token) {
        return store.doClearToken();
      } else {
        writeToken(token);
        dispatch({
          type: UPDATED,
          payload: token
        });
      }
    },
    doClearToken: () => ({
      dispatch
    }) => {
      clearToken();
      dispatch({
        type: CLEARED
      });
    },
    doUpdateTokenFromCookie: () => ({
      store
    }) => {
      const token = readToken();

      if (token !== store.selectAuthToken()) {
        store.doReceiveToken(token);
      }
    }
  };
};

exports.createTokenBundle = createTokenBundle;