import { Component, OnInit, OnDestroy } from '@angular/core';
import { ModalService } from '@libs/ui';
import { UserStateService } from '../../services/user-state.service';
import { Subject } from 'rxjs';
import { Router } from '@angular/router';
import { SsoService } from 'sso';
import { isNullOrUndefined } from 'util';
import { ErrorService } from './error.service';

@Component({
  selector: 'app-error',
  templateUrl: './error.component.html',
  styleUrls: ['./error.component.scss'],
})
export class ErrorComponent implements OnInit, OnDestroy {
  id = 'error-modal';
  errorOpened = false;
  message: string;
  destroy$ = new Subject();
  logout = false;
  safeMode = false;
  invalidAttributes: { key: string; value: string }[];
  hasInvalidAttributes = false;
  safeCodes = [400, 409];
  validMessageCodes = [0, 400, 404, 409, 500, 504];
  title = 'Irgendwas hat nicht funktioniert…';
  constructor(
    private modalService: ModalService,
    private stateService: UserStateService,
    private router: Router,
    private ssoService: SsoService,
    private errorService: ErrorService
  ) {}

  ngOnInit() {}

  openErrorModal({ code, message, invalidProperties, logout }) {
    if (!this.errorOpened) {
      this.safeMode = this.safeCodes.includes(code);
      this.hasInvalidAttributes = !isNullOrUndefined(invalidProperties);
      if (this.hasInvalidAttributes) {
        this.formatInvalidProperties(invalidProperties);
      }
      this.title = logout ? 'Willkommen zurück!' : 'Irgendwas hat nicht funktioniert…';
      this.message = logout ? 'Sie waren zu lange nicht in der ISA aktiv.<br>Bitte melden Sie sich erneut an.' : '';
      if (this.validMessageCodes.includes(code) && !isNullOrUndefined(message)) {
        this.message = message;
      }
      this.errorOpened = true;
      this.modalService.open(this.id);
    }
    this.logout = !this.logout ? logout : this.logout;
  }

  closeErrorModal() {
    if (this.logout) {
      this.ssoService.logoff();
      return;
    }
    this.errorOpened = false;
    this.errorService.addRecovery(true);
    this.modalService.close(this.id);
  }

  async resetState() {
    if (this.logout) {
      this.ssoService.logoff();
      return;
    }
    this.modalService.close(this.id);
    this.router.navigate(['/dashboard']);
    this.stateService.resetState().then(() => {
      window.location.reload();
    });
    this.errorOpened = false;
  }

  formatInvalidProperties(invalidProperties: string) {
    const properties = invalidProperties.replace('{', '').replace('}', '').replace(/"/g, '').split(',');
    if (properties && properties.length > 0) {
      this.invalidAttributes = properties.map((propertie) => {
        const keyValuePropertie = propertie.split(':');
        return { key: keyValuePropertie[0], value: keyValuePropertie[1] };
      });
    }
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.errorOpened = false;
  }
}
