import { fadeInAnimation } from './../../../product/pages/product-search/components/filter-item/fadeIn.animation';
import { Component, OnInit } from '@angular/core';
import { staggerAnimation } from './stagger.animation';
import { WindowRef } from 'apps/sales/src/app/core/services/window-ref.service';
import { AppService } from 'apps/sales/src/app/core/services/app.service';
import { SearchStateFacade } from '@shelf-store';
import { take } from 'rxjs/operators';
import { isNullOrUndefined } from 'util';

@Component({
  selector: 'app-shelf-search',
  templateUrl: './shelf-search.component.html',
  styleUrls: ['./shelf-search.component.scss'],
  animations: [staggerAnimation, fadeInAnimation],
})
export class ShelfSearchComponent implements OnInit {
  isIPad: boolean;
  private iPadDetected = false;
  private iPadEventReceived = false;
  constructor(private searchStateFacade: SearchStateFacade, private windowRef: WindowRef, private appService: AppService) {}

  ngOnInit() {
    this.isIPad = this.appService.isIPadEnv();
    this.restoreInitialState();
  }

  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.iPadEventReceived;
  }

  async restoreInitialState() {
    await this.createSearchEntityIfNotExists();
    this.resetPendingInput();
    this.resetFilters();
  }

  private async createSearchEntityIfNotExists() {
    const processId = await this.searchStateFacade.getProcessId();
    await this.searchStateFacade.getProcess$(processId).pipe(take(1)).toPromise();
  }

  private resetPendingInput() {
    this.searchStateFacade.setPendingInput('');
  }

  private resetFilters() {
    this.searchStateFacade.resetPrimaryFilters();
    this.searchStateFacade.resetSelectedFilters();
  }
}
