import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { ApplicationProcess, ApplicationService } from '@core/application';
import { DomainCheckoutService } from '@domain/checkout';
import { first } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class CanActivateCustomerGuard implements CanActivate {
  constructor(
    private readonly _applicationService: ApplicationService,
    private readonly _checkoutService: DomainCheckoutService,
    private readonly _router: Router
  ) {}

  async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    const processes = await this._applicationService.getProcesses$('customer').pipe(first()).toPromise();
    let lastActivatedProcessId = (
      await this._applicationService.getLastActivatedProcessWithSectionAndType$('customer', 'cart').pipe(first()).toPromise()
    )?.id;

    const lastActivatedCartProcessId = (
      await this._applicationService.getLastActivatedProcessWithSectionAndType$('customer', 'cart-checkout').pipe(first()).toPromise()
    )?.id;

    const activatedProcessId = await this._applicationService.getActivatedProcessId$().pipe(first()).toPromise();

    // Darf nur reinkommen wenn der aktuell aktive Tab ein Bestellabschluss Tab ist
    if (!!lastActivatedCartProcessId && lastActivatedCartProcessId === activatedProcessId) {
      await this.fromCheckoutCartProcess(processes, route, lastActivatedCartProcessId);
      return false;
    }

    if (!lastActivatedProcessId) {
      await this.fromCustomerProcess(processes);
      return false;
    } else {
      await this._router.navigate(['/kunde', String(lastActivatedProcessId), 'customer']);
    }
    return false;
  }

  // Bei offener Artikelsuche und Klick auf Footer Artikelsuche
  async fromCustomerProcess(processes: ApplicationProcess[]) {
    const newProcessId = Date.now();
    await this._applicationService.createProcess({
      id: newProcessId,
      type: 'cart',
      section: 'customer',
      name: `Vorgang ${processes.length + 1}`,
    });

    await this._router.navigate(['/kunde', String(newProcessId), 'customer']);
  }

  // Bei offener Bestellbestätigung und Klick auf Footer Artikelsuche
  async fromCheckoutCartProcess(processes: ApplicationProcess[], route: ActivatedRouteSnapshot, processId: number) {
    // Um alle Checkout Daten zu resetten die mit dem Prozess assoziiert sind
    this._checkoutService.removeProcess({ processId });

    // Ändere type cart-checkout zu cart
    this._applicationService.patchProcess(processId, {
      id: processId,
      type: 'cart',
      section: 'customer',
      name: `Vorgang ${processes.length + processes.filter((process) => process.type === 'cart-checkout').length}`,
      data: undefined,
    });

    // Navigation
    await this._router.navigate(['/kunde', String(processId), 'customer']);
  }
}
