"use strict";

var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");

exports.__esModule = true;
exports.default = void 0;

require("core-js/modules/es6.regexp.to-string");

var _createClass2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/createClass"));

var _now = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/date/now"));

var _stringify = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/json/stringify"));

var _md = _interopRequireDefault(require("crypto-js/md5"));

var _request = _interopRequireDefault(require("./request"));

/**
 * @description 封装游客服务
 * @example getGuestUser()
 */
var storage = {
  get(key) {
    try {
      return JSON.parse(window.localStorage.getItem(key));
    } catch (e) {
      throw new Error(e);
    }
  },

  set(key, value) {
    try {
      window.localStorage.setItem(key, (0, _stringify.default)(value));
    } catch (e) {
      throw new Error(e);
    }
  }

};

var GuestUser =
/*#__PURE__*/
function () {
  function GuestUser() {
    this.__guestfinger = null;
    this.guestFingerKey = 'guest_finger';
  }

  var _proto = GuestUser.prototype;

  _proto.login = function login() {
    return _request.default.post('/api/sessions', {
      guest_finger: this.guestfinger
    }).then(function (response) {
      return response.data;
    });
  };

  (0, _createClass2.default)(GuestUser, [{
    key: "guestfinger",
    get: function get() {
      if (this.__guestfinger) return this.__guestfinger;
      var guestfinger;

      try {
        guestfinger = storage.get(this.guestFingerKey);
      } catch (error) {
        guestfinger = null;
      }

      if (!guestfinger) {
        var text = `${location.href}_${(0, _now.default)()}_${Math.random()}`;
        guestfinger = (0, _md.default)(text).toString();
        storage.set(this.guestFingerKey, guestfinger);
        return guestfinger;
      }

      this.__guestfinger = guestfinger;
      return this.__guestfinger;
    }
  }]);
  return GuestUser;
}();

var _default = new GuestUser();

exports.default = _default;