import { Component, OnInit, OnDestroy } from '@angular/core';
import { Store } from '@ngxs/store';
import { fadeInAnimation } from '../../../../shared/animations/fade-in.animation';
import { staggerAnimation } from './stagger.animation';
import { ActivatedRoute } from '@angular/router';
import { UpdateCurrentBreadcrumbName } from '../../../../core/store/actions/breadcrumb.actions';
import { takeUntil, tap, switchMap } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { Location } from '@angular/common';
import { UpdateCurrentRouteQueryParams } from 'apps/sales/src/app/core/store/actions/process.actions';
import { WindowRef } from 'apps/sales/src/app/core/services/window-ref.service';
import { CustomerHelperService } from '../../services/customer-helper.service';
@Component({
  selector: 'app-customer-search',
  templateUrl: './customer-search.component.html',
  styleUrls: ['./customer-search.component.scss'],
  animations: [fadeInAnimation, staggerAnimation],
})
export class CustomerSearchComponent implements OnInit, OnDestroy {
  displayUserSearch = true;
  animate = false;
  isIPad = false;
  private iPadDetected = false;
  private iPadEventRecieved = false;
  titles = {
    search: 'Kundensuche',
    scan: 'Kundenkarte scannen',
    create: 'Kundendaten erfassen',
  };
  navigation = ['create', 'scan'];
  active = 'search';
  destroy$ = new Subject();

  constructor(
    private store: Store,
    private route: ActivatedRoute,
    private location: Location,
    private customerHelperService: CustomerHelperService,
    private windowRef: WindowRef
  ) {}

  ngOnInit() {
    this.isIPad = this.isIPadEnv();
    if (!this.isIPad) {
      this.navigation = ['create'];
    }
    this.route.params
      .pipe(takeUntil(this.destroy$))
      .pipe(
        tap((params) => {
          if (params['create'] || params['id']) {
            this.changeCards('create');
          }
        }),
        switchMap(() => {
          return this.route.queryParams;
        })
      )
      .subscribe((queryParams) => {
        if (queryParams['card']) {
          this.changeCards(queryParams['card']);
          this.isIPad = this.isIPadEnv();
          if (!this.isIPad) {
            if (queryParams['card'] === 'create') {
              this.navigation = ['search'];
            } else {
              this.navigation = ['create'];
            }
          }
        } else {
          this.changeCards('search');
        }
      });

    this.customerHelperService.resetCustomerSearchView$.pipe(takeUntil(this.destroy$)).subscribe(() => this.changeCards('search'));
  }

  changeCard() {
    this.animate = true;
    this.displayUserSearch = !this.displayUserSearch;
    this.animate = false;
  }

  switch(newItem: string) {
    const index = this.navigation.indexOf(newItem);
    this.navigation[index] = this.active;
    this.active = newItem;
    this.store.dispatch(new UpdateCurrentBreadcrumbName(this.titles[this.active], 'customer', { card: newItem }));
    this.store.dispatch(new UpdateCurrentRouteQueryParams({ card: newItem }));
    this.location.go('/customer/search', `card=${newItem}`);
  }

  changeCards(newItem: string) {
    const index = this.navigation.indexOf(newItem);
    this.navigation[index] = this.active;
    this.active = newItem;
  }

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

  isIPadEnv() {
    const navigator = this.windowRef.nativeWindow.navigator as Navigator;
    const standalone = (navigator as any).standalone,
      userAgent = navigator.userAgent.toLowerCase(),
      ios = /iphone|ipod|ipad/.test(userAgent);

    this.iPadDetected = ios && !standalone;
    return this.iPadDetected || this.iPadEventRecieved;
  }
}
