import { Component, OnInit, OnDestroy } from '@angular/core';
import { fadeInAnimation } from '../../../../shared/animations/fade-in.animation';
import { staggerAnimation } from './stagger.animation';
import { Store } from '@ngxs/store';
import { UpdateCurrentBreadcrumbName } from '../../../../core/store/actions/breadcrumb.actions';
import { ActivatedRoute } from '@angular/router';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { Location } from '@angular/common';
import { WindowRef } from 'apps/sales/src/app/core/services/window-ref.service';

@Component({
  selector: 'app-product-search',
  templateUrl: './product-search.component.html',
  styleUrls: ['./product-search.component.scss'],
  animations: [fadeInAnimation, staggerAnimation],
})
export class ProductSearchComponent implements OnInit, OnDestroy {
  titles = {
    search: 'Artikelsuche',
    scan: 'Artikel scannen',
  };
  navigation = ['scan'];
  active = 'search';
  destroy$ = new Subject();
  isIPad: boolean;
  private iPadDetected = false;
  private iPadEventRecieved = false;
  constructor(private store: Store, private route: ActivatedRoute, private location: Location, private windowRef: WindowRef) {}

  ngOnInit() {
    this.isIPad = this.isIPadEnv();
    this.route.queryParams.pipe(takeUntil(this.destroy$)).subscribe((params) => {
      if (params && params['path'] === 'scan') {
        this.changeCards('scan');
      } else if (params && params['path'] === 'search') {
        this.changeCards('search');
      }
    });
  }

  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], 'product', { path: newItem }));
    this.location.go('/product/search', `path=${newItem}`);
  }

  changeCards(newItem: string) {
    const index = this.navigation.indexOf(newItem);
    this.navigation[index] = this.active;
    this.active = newItem;
    this.location.go('/product/search', `path=${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;
  }
}
