import { Injectable } from '@angular/core';

const KEY_USER = 'userName';
const KEY_SESSION_ID = 'sessionTempId';
const KEY_REDIRECT_URL = 'redirectAfterLogin';
const KEY_USER_TOKEN = 'userToken';
const KEY_USER_ID = 'userId';
@Injectable({
  providedIn: 'root'
})

export class SessionService {

  constructor() { }

  public get currentUserName(): string {
    return this.getLocalStorage(KEY_USER, '');
  }
  public set currentUserName(v: string) {
    this.setLocalStorage(KEY_USER, v);
  }

  public get sessionId(): string {
    return this.getLocalStorage(KEY_SESSION_ID, Guid.newGuid());
  }
  public set sessionId(v: string) {
    this.setLocalStorage(KEY_SESSION_ID, v);
  }

  public get redirectAfterLogin(): string {
    return this.getLocalStorage(KEY_REDIRECT_URL, '');
  }
  public set redirectAfterLogin(v: string) {
    this.setLocalStorage(KEY_REDIRECT_URL, v);
  }

  public get loginUserToken(): string {
    return this.getLocalStorage(KEY_USER_TOKEN, '');
  }
  public set loginUserToken(v: string) {
    this.setLocalStorage(KEY_USER_TOKEN, v);
  }
  public get loginUserId(): string {
    return this.getLocalStorage(KEY_USER_ID, '');
  }
  public set loginUserId(v: string) {
    this.setLocalStorage(KEY_USER_ID, v);
  }

  public setLocalStorage(key: string, value: string) {
    localStorage.setItem(key, value);
  }
  public getLocalStorage(key: string, defaultValue: string = null): string {

    let _sessionId = localStorage.getItem(key);
    if (!_sessionId) {
      this.sessionId = defaultValue;
    }
    return localStorage.getItem(key);
  }

}
class Guid {
  static newGuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      var r = Math.random() * 16 | 0,
        v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }
}