import { Component } from '@angular/core';
import { NavStateService } from '@armor/brandkit';
import { HttpClient } from '@angular/common/http';

import { NAV_ITEMS } from './app.nav';
import { LoginService } from '@armor/api';
import { CONFIGURATION_CONTEXT, LocalStorageService, WindowService } from '@armor/platform-browser';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  constructor(
    private loginService: LoginService,
    private navStateService: NavStateService,
    private windowService: WindowService,
    private localStorageService: LocalStorageService,
    private _httpClient: HttpClient
  ) {
    this.httpClient = _httpClient;

    // Initialize navigation state service.
    this.navState = this.navStateService.state;
    this.navStateService.navStateChanged$.subscribe((_state: string) => {
      this.onNavStateChanged(_state);
    });

    this.window = windowService.getWindowReference();
    this.loginService.handleAuthorizationCode(() => {
      // Add functions here if you need to globally trigger anything after authorization/identity is processed.
      // TODO: Add code to register the fullstory user.

      // TODO: remove this redundant pushState call
      // It is working from the IMC & AMP, but somethign about the current routing on create-armor-ui
      // is making it so that it needs the extra setTimeout to work correctly
      setTimeout(() => {
        const url = this.router.url.replace(new RegExp('[?&]authorization_code=[^&#]*(#.*)?$'), '$1');
        window.history.pushState({ authCodeProcessed: true }, window.document.title, url);
      });

      // TODO: Remove this code once proper idle logout handling is in place.
      setInterval(() => {
        this.requestReissue();
      }, 100000);
    });
  }

  public navItems: any[] = NAV_ITEMS;
  public navState: string;
  public window: any;
  public httpClient: HttpClient;

  public onNavStateChanged(_state: string) {
    this.navState = _state;
  }

  public requestReissue() {
    // TODO: Remove this code once proper idle logout handling is in place.
    this.httpClient.post(`${CONFIGURATION_CONTEXT.instance.endpoints.api}auth/token/reissue`,
      { token: this.localStorageService.get('auth-token') },
      {
        headers: {
          Authorization: `FH-AUTH ${ this.localStorageService.get('auth-token') }`,
          'Content-Type': 'application/json'
        }
      }
    ).subscribe((response: any) => {
      console.log(`[AMP] Token reissued. New token is "${ response.access_token }"`);
      this.localStorageService.set('auth-token', response.access_token);
    });
  }
}
