"use strict";

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

var _jwtDecode = _interopRequireDefault(require("jwt-decode"));

var _v = _interopRequireDefault(require("uuid/v4"));

var _keychain = _interopRequireDefault(require("./keychain"));

var _api = require("./api");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * External dependencies
 */

/**
 * Internal dependencies
 */
// Config
const SERVICE = 'vip-go-cli';
exports.SERVICE = SERVICE;

class Token {
  constructor(token) {
    if (!token) {
      return;
    }

    token = token.trim();

    if (!token.length) {
      return;
    }

    const t = (0, _jwtDecode.default)(token);
    this.raw = token;

    if (t.id) {
      this.id = t.id;
    }

    if (t.iat) {
      this.iat = new Date(t.iat * 1000);
    }

    if (t.exp) {
      this.exp = new Date(t.exp * 1000);
    }
  }

  valid() {
    if (!this.id) {
      return false;
    }

    if (!this.iat) {
      return false;
    }

    const now = new Date();

    if (!this.exp) {
      return now > this.iat;
    }

    return now > this.iat && now < this.exp;
  }

  expired() {
    if (!this.exp) {
      return false;
    }

    const now = new Date();
    return now > this.exp;
  }

  static async uuid() {
    const service = Token.getServiceName('-uuid');

    let _uuid = await _keychain.default.getPassword(service);

    if (!_uuid) {
      _uuid = (0, _v.default)();
      await _keychain.default.setPassword(service, _uuid);
    }

    return _uuid;
  }

  static async setUuid(_uuid) {
    const service = Token.getServiceName('-uuid');
    await _keychain.default.setPassword(service, _uuid);
  }

  static async set(token) {
    const service = Token.getServiceName();
    return _keychain.default.setPassword(service, token);
  }

  static async get() {
    const service = Token.getServiceName();
    const token = await _keychain.default.getPassword(service);
    return new Token(token);
  }

  static async purge() {
    const service = Token.getServiceName();
    return _keychain.default.deletePassword(service);
  }

  static getServiceName(modifier = '') {
    let service = SERVICE;

    if (_api.PRODUCTION_API_HOST !== _api.API_HOST) {
      const sanitized = _api.API_HOST.replace(/[^a-z0-9]/gi, '-');

      service = `${SERVICE}:${sanitized}`;
    }

    return `${service}${modifier}`;
  }

}

exports.default = Token;