import _Date$now from "@babel/runtime-corejs2/core-js/date/now";
import _JSON$stringify from "@babel/runtime-corejs2/core-js/json/stringify";

/**
 * @description 封装游客服务
 * @example getGuestUser()
 */
import md5 from 'crypto-js/md5';
import request from './request';
const 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, _JSON$stringify(value));
    } catch (e) {
      throw new Error(e);
    }
  }

};

class GuestUser {
  constructor() {
    this.__guestfinger = null;
    this.guestFingerKey = 'guest_finger';
  }

  get guestfinger() {
    if (this.__guestfinger) return this.__guestfinger;
    let guestfinger;

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

    if (!guestfinger) {
      const text = `${location.href}_${_Date$now()}_${Math.random()}`;
      guestfinger = md5(text).toString();
      storage.set(this.guestFingerKey, guestfinger);
      return guestfinger;
    }

    this.__guestfinger = guestfinger;
    return this.__guestfinger;
  }

  login() {
    return request.post('/api/sessions', {
      guest_finger: this.guestfinger
    }).then(response => response.data);
  }

}

export default new GuestUser();