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

/**
 * @description 封装游客服务
 * @example getGuestUser()
 */
import md5 from 'crypto-js/md5';
import request from '../request';
import cache from '../cache';

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

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

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

    if (!guestfinger) {
      const text = `${location.href}_${_Date$now()}_${Math.random()}`;
      guestfinger = md5(text).toString();
      cache.localCache.set(this.guestFingerKey, guestfinger, {
        time: '356d'
      });
      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();