import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { ApplicationService } from '@core/application';
import { BreadcrumbService } from '@core/breadcrumb';
import { CacheService } from '@core/cache';
import { Config } from '@core/config';
import { ToastService } from '@core/toast';
import { Subject } from 'rxjs';
import { filter, first, takeUntil } from 'rxjs/operators';
import { RemissionListComponentStore } from './remission-list/remission-list.component-store';

@Component({
  selector: 'page-remission',
  templateUrl: './remission.component.html',
  styleUrls: ['./remission.component.scss'],
  providers: [RemissionListComponentStore],
})
export class RemissionComponent implements OnInit, OnDestroy {
  private _onDestroy$ = new Subject();

  get processId() {
    return this._config.get('process.ids.remission');
  }

  constructor(
    private readonly _remissionListComponentStore: RemissionListComponentStore,
    private readonly _breadcrumb: BreadcrumbService,
    private readonly _config: Config,
    private _activatedRoute: ActivatedRoute,
    private _applicationService: ApplicationService,
    private _router: Router,
    private _cache: CacheService,
    private _toastService: ToastService
  ) {}

  ngOnInit(): void {
    this.addBreadcrumbIfNotExists();

    this._router.events
      ?.pipe(
        filter((event) => event instanceof NavigationEnd),
        takeUntil(this._onDestroy$)
      )
      .subscribe(() => {
        this.updateProcess();
      });

    this.updateProcess();
  }

  ngOnDestroy(): void {
    this._onDestroy$.next();
    this._onDestroy$.complete();
    this.createToast();
  }

  addBreadcrumbIfNotExists() {
    this._breadcrumb.addBreadcrumbIfNotExists({
      key: this.processId,
      name: 'Remission',
      path: '/filiale/remission',
      section: 'branch',
      tags: ['remission'],
    });
  }

  async updateProcess() {
    const params = this._activatedRoute.snapshot.firstChild.params;
    const queryParams = this._activatedRoute.snapshot.queryParams ?? {};
    if (!!params?.returnId) {
      this._applicationService.patchProcess(this.processId, {
        closeable: false,
        data: { active: +params.returnId, queryParams },
      });
    } else {
      this.clearCache();
      this._applicationService.patchProcess(this.processId, {
        closeable: true,
        data: {},
      });
    }
  }

  clearCache() {
    this._cache.delete({ processId: String(this.processId) });
  }

  async createToast() {
    const process = await this._applicationService.getProcessById$(this.processId).pipe(first()).toPromise();
    if (process?.data?.active) {
      this._toastService.create({
        title: 'Wannendeckel Auflegen',
        text: 'Wenn Sie die Remission unterbrechen legen Sie den Wannendeckel auf die Wanne.',
      });
    }
  }
}
