import { Injectable } from '@angular/core';
import { ConfigService } from '@shared/config/config.service';
import { CookiesHelper } from '@shared/ui-api/helpers/cookies-helper';

@Injectable({
  providedIn: 'root'
})
export class TokenStorageService {
  constructor(private config: ConfigService) {
  }

  private reformatExpireAt(expireAt: string): string {
    // ensure the format works with cookies
    if (expireAt) {
      const expireAtDate = new Date(expireAt);
      return expireAtDate.toUTCString();
    }
    return expireAt;
  }

  getTokenName(panelName?: string): string {
    return `${panelName || this.config.currentConfigurationName}-fleio-token`;
  }

  getToken(): string {
    return CookiesHelper.getCookie(this.getTokenName());
  }

  setToken(tokenValue: string, expireAt, expireAtBrowserClose) {
    expireAt = this.reformatExpireAt(expireAt);
    CookiesHelper.setCookie(
      this.getTokenName(), tokenValue, null, expireAt, expireAtBrowserClose, 'Lax'
    );
  }

  setPanelToken(panelName: string, tokenValue: string, expireAt, expireAtBrowserClose) {
    expireAt = this.reformatExpireAt(expireAt);
    CookiesHelper.setCookie(
      this.getTokenName(panelName), tokenValue, null, expireAt, expireAtBrowserClose, 'Lax'
    );
  }

  clearToken() {
    CookiesHelper.clearCookie(this.getTokenName());
  }

  getPanelToken(panelName: string) {
    return CookiesHelper.getCookie(this.getTokenName(panelName));
  }

  clearPanelToken(panelName: string) {
    CookiesHelper.clearCookie(this.getTokenName(panelName));
  }
}
