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

@Injectable({ providedIn: 'root' })
export class CanActivateGoodsInGuard implements CanActivate {
  constructor(private readonly _applicationService: ApplicationService, private readonly _config: Config) {}

  async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    const process = await this._applicationService.getProcessById$(this._config.get('process.ids.goodsIn')).pipe(first()).toPromise();
    if (!process) {
      await this._applicationService.createProcess({
        id: this._config.get('process.ids.goodsIn'),
        type: 'goods-in',
        section: 'branch',
        name: 'Abholfach',
      });
    }
    this._applicationService.activateProcess(this._config.get('process.ids.goodsIn'));
    return true;
  }
}
