import { Component, OnInit, Output, EventEmitter, OnDestroy } from '@angular/core';
import { Store } from '@ngxs/store';
import { RemissionSelectors } from '../../../core/store/selectors/remission.selectors';
import { ChangeCurrentRoute, ResetProcessProductFilters } from '../../../core/store/actions/process.actions';
import { Router } from '@angular/router';
import { DeleteLastPreviousPath, UpdateActiveCrumb, ResetBreadcrumbsTo } from '../../../core/store/actions/breadcrumb.actions';
import { SharedSelectors } from '../../../core/store/selectors/shared.selectors';
import { ResetFilters } from '../../../core/store/actions/filter.actions';
import {
  ResetRemissionState,
  SetRemissionFinishedProcessStatus,
  SetRemissionStarted,
  ResetRemissionShippingDocument,
  SetRemissionShippingDocument,
  RequestDeleteShippingDocument,
  DeleteRemissionShippingDocument,
} from './../../../core/store/actions/remission.actions';
import { ModuleSwitcher } from '../../../core/models/app-switcher.enum';
import { SetBranchProcessCurrentPath } from '../../../core/store/actions/branch-process.actions';
import { AppService } from '../../../core/services/app.service';
import { RemissionFinishingProcessStatus } from '../../../modules/remission/models/remission-finishing-process-status.enum';
import { Breadcrumb } from '../../../core/models/breadcrumb.model';
import { AppState } from '../../../core/store/state/app.state';
import { takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { FILIALE_LANDING_PAGE } from '../../../core/utils/app.constants';

@Component({
  selector: 'app-back-arrow',
  templateUrl: './back-arrow.component.html',
  styleUrls: ['./back-arrow.component.scss'],
})
export class BackArrowComponent implements OnInit, OnDestroy {
  @Output() back = new EventEmitter();
  module: ModuleSwitcher;
  destroy$ = new Subject();

  constructor(private appService: AppService, private store: Store, private router: Router) {}

  ngOnInit() {
    this.store
      .select(AppState.activeModule)
      .pipe(takeUntil(this.destroy$))
      .subscribe((v: ModuleSwitcher) => {
        this.module = v;
      });
  }

  ngOnDestroy(): void {
    this.destroy$.next();
  }

  emitClick() {
    const previousRoute = this.store.selectSnapshot(SharedSelectors.getPreviousRoute);
    if (previousRoute) {
      if (this.router.url === '/remission/finish') {
        const processStatus = this.store.selectSnapshot(RemissionSelectors.getRemissionFinishingProcessStatus);
        if (processStatus === RemissionFinishingProcessStatus.start) {
          this.store.dispatch(new SetRemissionFinishedProcessStatus(RemissionFinishingProcessStatus.notSet));
        } else {
          this.store.dispatch(new SetRemissionFinishedProcessStatus(RemissionFinishingProcessStatus.notSet));
          this.navigateToNewRemissionList();
          return;
        }
      }
      if (previousRoute.path === '/remission/finish') {
        this.store.dispatch(new SetRemissionFinishedProcessStatus(RemissionFinishingProcessStatus.containerScanned));
        const shippingDocument = this.store.selectSnapshot(RemissionSelectors.getRemissionShippingDocument);
        this.store.dispatch(new SetRemissionShippingDocument(shippingDocument));
      }
      if (this.isBrowserBackToCreatePageFromStartedPage(previousRoute.path)) {
        const shipingDocumentProductCount = this.store.selectSnapshot(RemissionSelectors.getRemissionShippingDocumentProductCount);
        if (shipingDocumentProductCount === 0) {
          const existingRemission = this.store.selectSnapshot(RemissionSelectors.getRemissionProcess);
          this.store.dispatch(new RequestDeleteShippingDocument(existingRemission));
          return;
        } else {
          this.appService.openStartedRemissionLeavingDialog();
          return;
        }
      }
      if (previousRoute.path === '/product/search') {
        this.store.dispatch(new ResetFilters());
        this.store.dispatch(new ResetProcessProductFilters());
      }
      if (this.module === ModuleSwitcher.Customer) {
        this.store.dispatch(new ChangeCurrentRoute(previousRoute.path, true));
      } else {
        this.store.dispatch(new SetBranchProcessCurrentPath(previousRoute.path, true));
      }
      this.store.dispatch(new DeleteLastPreviousPath());
      this.store.dispatch(new UpdateActiveCrumb(previousRoute.crumb));
      if (this.checkIfPathHasQueryParams(previousRoute.path)) {
        const cleanPath = this.getCleanPath(previousRoute.path);
        const queryParams = this.getParams(previousRoute.path);
        this.router.navigate([cleanPath], { queryParams: queryParams });
      } else {
        this.router.navigate([previousRoute.path]);
      }
    } else {
      this.router.navigate([this.module === ModuleSwitcher.Customer ? '/dashboard' : FILIALE_LANDING_PAGE]);
    }
  }

  private navigateToNewRemissionList() {
    this.store.dispatch(new ResetRemissionState());
    const path = '/remission/create';
    this.store.dispatch(
      new ResetBreadcrumbsTo(
        <Breadcrumb>{
          name: 'Remission',
          path: path,
        },
        'remission',
        true
      )
    );
    this.store.dispatch(new SetBranchProcessCurrentPath(path));
    this.router.navigate([path]);
  }

  private checkIfPathHasQueryParams(path: string) {
    const hasParams = path.includes('?');
    return hasParams;
  }

  private getCleanPath(path: string) {
    const queryParamsStartIndex = path.indexOf('?');
    return path.substring(0, queryParamsStartIndex);
  }

  private getParams(path: string) {
    const queryParamsStartIndex = path.indexOf('?') + 1;
    const paramsStr = path.substring(queryParamsStartIndex);
    const paramsList = paramsStr.split('&');
    const params = {};
    paramsList.forEach((param) => {
      const keyVal = param.split('=');
      params[keyVal[0]] = keyVal[1];
    });
    return params;
  }

  private isBrowserBackToCreatePageFromStartedPage(path: string): boolean {
    return path === '/remission/create' && this.router.url !== '/remission/overview';
  }
}
