'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getCookieToken = getCookieToken;
exports.setAccessToken = setAccessToken;
exports.getAccessToken = getAccessToken;
exports.removeAccessToken = removeAccessToken;

var _cookie = require('./cookie');

var _constants = require('./constants');

var cachedToken = null;

var localReg = /localhost/g;

function getCookieToken() {
  var option = {
    path: '/'
  };
  var token = (0, _cookie.getCookie)(_constants.ACCESS_TOKEN, option);
  if (token && cachedToken && token !== cachedToken) {
    return null;
  }
  return token;
}

/**
 * 前端存储cookie token
 */
function setAccessToken(token, tokenType, expiresIn) {
  var option = {
    path: '/'
  };
  if (expiresIn) {
    var expires = expiresIn * 1000;
    option.expires = new Date(Date.now() + expires);
  }
  if (!_constants.LOCAL && !localReg.test(window.location.host) && (0, _cookie.getCookie)(_constants.ACCESS_DOMAIN) === null) {
    option.domain = _constants.COOKIE_SERVER;
  }
  (0, _cookie.setCookie)(_constants.ACCESS_TOKEN, token, option);
  (0, _cookie.setCookie)(_constants.TOKEN_TYPE, tokenType, option);
  cachedToken = token;
}

/**
 * 获取cookie token
 */
function getAccessToken() {
  var option = {
    path: '/'
  };
  var accessToken = getCookieToken();
  var tokenType = (0, _cookie.getCookie)(_constants.TOKEN_TYPE, option);
  if (accessToken && tokenType) {
    return tokenType + ' ' + accessToken;
  }
  return null;
}

/**
 * 移除token
 */
function removeAccessToken() {
  var option = {
    path: '/'
  };
  if (!_constants.LOCAL && !localReg.test(window.location.host)) {
    option.domain = _constants.COOKIE_SERVER;
  }
  (0, _cookie.removeCookie)(_constants.ACCESS_TOKEN, option);
  (0, _cookie.removeCookie)(_constants.TOKEN_TYPE, option);
}