import { Component, OnInit, Input, ChangeDetectionStrategy, ChangeDetectorRef, ViewChild, ElementRef, HostListener } from '@angular/core';
import { FeedCard } from '../../../../core/models/feed-card.model';
import { Breadcrumb } from '../../../../core/models/breadcrumb.model';
import { AddBreadcrumb, PopBreadcrumbsBeforeCurrent } from '../../../../core/store/actions/breadcrumb.actions';
import { ChangeCurrentRoute, AddProcess } from '../../../../core/store/actions/process.actions';
import { Store, Select } from '@ngxs/store';
import { Router } from '@angular/router';
import { Process } from '../../../../core/models/process.model';
import { Observable } from 'rxjs';
import { ProcessSelectors } from '../../../../core/store/selectors/process.selectors';
import { WindowRef } from 'apps/sales/src/app/core/services/window-ref.service';

@Component({
  selector: 'app-book-card',
  templateUrl: './book-card.component.html',
  styleUrls: ['./book-card.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class BookCardComponent implements OnInit {
  @ViewChild('books', { read: ElementRef, static: true }) public books: ElementRef<any>;
  @Select(ProcessSelectors.getProcesses) processes$: Observable<Process[]>;
  @Input() card: FeedCard;
  isIPad: boolean;
  private iPadDetected = false;
  private iPadEventRecieved = false;
  showForward = false;
  showForwarContainer = true;
  showBack = false;
  showBackContainer = false;
  offset: number;

  constructor(private store: Store, private router: Router, private cdrf: ChangeDetectorRef, private windowRef: WindowRef) {}

  ngOnInit() {
    this.isIPad = this.isIPadEnv();
    if (this.isIPad) {
      this.showForwarContainer = false;
      this.showBackContainer = false;
    }
    if (this.card && this.card.books && this.card.books.length < 4) {
      this.showForwarContainer = false;
      this.showBackContainer = false;
    }
    this.offset = Math.ceil(this.books.nativeElement.clientWidth / 2);
  }

  details(ean: string, name: string) {
    const processExist = this.store.selectSnapshot(ProcessSelectors.getProcesses).length > 0;
    if (!processExist) {
      this.createProcess();
    }

    const dashboardBread = {
      name: 'Dashboard',
      path: '/dashboard',
    };

    const path = '/product/details/' + ean;
    const queryParams = { type: 'ean' };
    const newBread: Breadcrumb = {
      name: name.substring(0, 12) + (name.length > 12 ? '...' : ''),
      path,
      queryParams,
    };

    this.store.dispatch(new PopBreadcrumbsBeforeCurrent('product'));
    this.store.dispatch(new AddBreadcrumb(dashboardBread, 'product'));
    this.store.dispatch(new AddBreadcrumb(newBread, 'product'));
    this.store.dispatch(new ChangeCurrentRoute(path, false, queryParams));
    this.router.navigate([path], {
      queryParams,
    });
  }

  createProcess() {
    const newProcess = <Process>{
      id: 1,
      name: 'Vorgang 1',
    };
    this.store.dispatch(new AddProcess(newProcess));
  }

  showFowardIcon() {
    if (this.card && this.card.books && this.card.books.length < 4) {
      return;
    }
    this.showForward = true;
    this.cdrf.detectChanges();
  }

  hideFowardIcon(event) {
    const e = event.toElement || event.relatedTarget;
    if (e && e.classList && (e.classList[0] === 'icon' || e.classList[0] === 'ng-star-inserted')) {
      return;
    }
    this.showForward = false;
  }

  showBackIcon() {
    this.showBack = true;
  }

  hideBackIcon(event) {
    const e = event.toElement || event.relatedTarget;
    if (e && e.classList && (e.classList[0] === 'icon' || e.classList[0] === 'ng-star-inserted')) {
      return;
    }
    this.showBack = false;
  }

  scrollForward(event) {
    if (event) {
      event.stopPropagation();
      const newScrollLeftPosition = this.books.nativeElement.scrollLeft + 102 * 3;
      const scrollLeft =
        newScrollLeftPosition + this.offset * 2 > this.books.nativeElement.scrollWidth
          ? this.books.nativeElement.scrollWidth
          : newScrollLeftPosition;
      this.books.nativeElement.scrollTo({
        left: scrollLeft,
        behavior: 'smooth',
      });
      this.showForwarContainer = scrollLeft + this.offset * 2 < this.books.nativeElement.scrollWidth;
      this.showBackContainer = true;
      this.showBack = false;
    }
  }

  scrollBack(event) {
    if (event) {
      event.stopPropagation();
      const newScrollLeftPosition = this.books.nativeElement.scrollLeft - 102 * 3;
      const scrollLeft = newScrollLeftPosition + this.offset * 2 < 0 ? this.books.nativeElement.scrollWidth : newScrollLeftPosition;
      this.books.nativeElement.scrollTo({
        left: scrollLeft,
        behavior: 'smooth',
      });
      this.showBackContainer = this.books.nativeElement.scrollLeft - this.offset > 0;
      this.showForwarContainer = true;
      this.showForward = false;
    }
  }

  @HostListener('window:scroll', ['$event'])
  scrollHandler(event) {
    event.stopPropagation();
    if (this.isIPad) {
      return;
    }
    if (this.books.nativeElement.scrollLeft > 0) {
      this.showBackContainer = true;
    } else {
      this.showBackContainer = false;
    }
    this.showBack = false;
    this.showForwarContainer = this.books.nativeElement.scrollLeft + this.offset * 2 < this.books.nativeElement.scrollWidth;
    this.showForward = false;
  }

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