import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { ApplicationService } from '@core/application';
import { Config } from '@core/config';
import { first, map } from 'rxjs/operators';

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

  async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    const processesIds = await this._applicationService
      .getProcesses$('customer')
      .pipe(
        first(),
        map((p) => {
          return p.filter((process) => process.type === 'goods-out').map((process) => +process.name.replace('Warenausgabe', '').trim());
        })
      )
      .toPromise();

    let lastActivatedProcessId = (
      await this._applicationService.getLastActivatedProcessWithSectionAndType$('customer', 'goods-out').pipe(first()).toPromise()
    )?.id;

    if (!lastActivatedProcessId) {
      lastActivatedProcessId = Date.now();
      await this._applicationService.createProcess({
        id: lastActivatedProcessId,
        type: 'goods-out',
        section: 'customer',
        name: `Warenausgabe`,
      });
    }

    await this._router.navigate(this.getUrlFromSnapshot(route, ['/kunde', String(lastActivatedProcessId)]));
    return false;
  }

  getUrlFromSnapshot(route: ActivatedRouteSnapshot, url: string[] = []): string[] {
    url.push(...route.url.map((segment) => segment.path));
    if (route.firstChild) {
      return this.getUrlFromSnapshot(route.firstChild, url);
    }
    return url.filter((segment) => !!segment);
  }
}
