import { Injectable } from '@angular/core';
import { CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Store } from '@ngxs/store';
import { Observable } from 'rxjs';
import { filter } from 'rxjs/operators';

import { AppService, ModalConfirmationService } from '@sales/core-services';

import { RemissionListStartedComponent } from './../pages/remission-list-started/remission-list-started.component';
import { RemissionFinishComponent } from './../pages/remission-finish/remission-finish.component';
import { ROUTES } from './../remission.const';
import { RemissionSelectors } from '../../../core/store/selectors/remission.selectors';

@Injectable({
  providedIn: 'root',
})
export class CanDeactivatedGuard implements CanDeactivate<RemissionListStartedComponent | RemissionFinishComponent> {
  constructor(private appService: AppService, private modalConfirmationService: ModalConfirmationService, private store: Store) {}

  canDeactivate(
    component: RemissionListStartedComponent | RemissionFinishComponent,
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot,
    nextState: RouterStateSnapshot
  ): Observable<boolean> | boolean {
    if (!nextState.url.includes(ROUTES.BASE) && !this.noRemissionProcess()) {
      this.appService.showLeavingRemissionModal();
      const obs$ = this.modalConfirmationService.afterClosed();
      obs$.pipe(filter((result) => result)).subscribe((_) => {
        this.appService.registerNotIdleRemissionReminder();
      });
      return obs$;
    } else {
      return true;
    }
  }

  private noRemissionProcess() {
    const remissionProcess = this.store.selectSnapshot(RemissionSelectors.getRemissionProcess);
    const remissionProcessStatuses = this.store.selectSnapshot(RemissionSelectors.getRemissionProcessStatuses);
    const { created } = remissionProcessStatuses
      ? this.store.selectSnapshot(RemissionSelectors.getRemissionProcessStatuses)
      : { created: false };
    return !remissionProcess || !created;
  }
}
