import { storage } from './storage';

class Session {
  init(data: any, skipToken?: boolean) {
    const { access_token, refresh_token, ...dbUser } = data;
    this.setUserInfo(dbUser);
    if (!skipToken) {
      this.setAccessToken(access_token);
      this.setRefreshToken(refresh_token);
    }
  }

  get() {
    return storage.local.get('x-idm-user-info') || {};
  }

  getAccessToken() {
    return storage.local.get('x-idm-access-token') || '';
  }

  getRefreshToken() {
    return storage.local.get('x-idm-refresh-token') || '';
  }

  /**
   * OpenIM的登录信息
   */
  getOpenIMInfo() {
    return storage.local.get('x-idm-openIM-info') || {};
  }

  destroy() {
    storage.local.remove('x-idm-access-token');
    storage.local.remove('x-idm-refresh-token');
    storage.local.remove('x-idm-user-info');
    storage.local.remove('x-idm-openIM-info');
  }

  setAccessToken(accessToken: string) {
    storage.local.set('x-idm-access-token', accessToken);
  }

  setRefreshToken(refreshToken: string) {
    storage.local.set('x-idm-refresh-token', refreshToken);
  }


  setUserInfo(user: any) {
    storage.local.set('x-idm-user-info', user);
  }


  setOpenIMInfo(openIMToken: string) {
    storage.local.set('x-idm-openIM-info', openIMToken);
  }
}

export const session = new Session();
export default session;
