import {
  Component,
  OnInit,
  ViewChild,
  ElementRef,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Input,
  HostListener,
  AfterViewInit,
  HostBinding,
} from '@angular/core';
import { ChangeCurrentRoute } from '../../../../core/store/actions/process.actions';
import { Store } from '@ngxs/store';
import { Router } from '@angular/router';
import { OtherFormats } from '../../../../core/models/other-formats.model';
import { isNullOrUndefined } from 'util';
import { WindowRef } from 'apps/sales/src/app/core/services/window-ref.service';

@Component({
  selector: 'app-product-other-formats',
  templateUrl: './product-other-formats.component.html',
  styleUrls: ['./product-other-formats.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProductOtherFormatsComponent implements OnInit {
  @ViewChild('formats', { read: ElementRef }) public formats: ElementRef<any>;
  showNext = false;
  showBack = false;
  showFowardContainer = false;
  showBackContainer = false;
  offset: number;
  selectedFormatId: string;
  selectedFormat: any;
  topPosition: number;
  isIPad: boolean;
  private iPadDetected = false;
  private iPadEventRecieved = false;

  @Input() detailsExpanded: boolean;

  _formats: OtherFormats[];
  @Input() set productFormats(inputFormats) {
    this._formats = inputFormats;
    this.cdr.detectChanges();
    this.initShowArrows();
    this.scrollToBegining();
  }

  get productFormats() {
    return this._formats;
  }

  @HostBinding('style.padding-bottom') bottomPadding: string;

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

  ngOnInit() {
    this.isIPad = this.isIPadEnv();
    if (this.isIPad === true) {
      this.bottomPadding = '50px';
    }
    this.cdr.detectChanges();
  }

  initShowArrows() {
    this.cdr.detectChanges();
    this.offset = Math.ceil(this.formats.nativeElement.clientWidth / 2);

    const lastformat = this.formats.nativeElement.children[this.formats.nativeElement.children.length - 2];

    if (lastformat) {
      const lastPos = lastformat.offsetLeft + lastformat.offsetWidth;
      this.showFowardContainer = lastPos / 2 > this.formats.nativeElement.clientWidth;
      this.cdr.detectChanges();
    }
  }

  scrollToBegining() {
    this.formats.nativeElement.scrollLeft = 0;
    this.showBack = false;
    this.showBackContainer = false;
    this.cdr.detectChanges();
  }

  scrollBack() {
    const moveCalc = this.formats.nativeElement.scrollLeft - this.offset;
    this.formats.nativeElement.scrollTo({ left: moveCalc, behavior: 'smooth' });
    this.cdr.detectChanges();

    this.showBackContainer = this.formats.nativeElement.scrollLeft - this.offset > 0;
    this.showBack = false;

    this.showFowardContainer = this.formats.nativeElement.scrollLeft < this.formats.nativeElement.scrollWidth;
    this.showNext = false;

    this.cdr.detectChanges();
  }

  scrollFoward() {
    const moveCalc = this.formats.nativeElement.scrollLeft + this.offset;
    this.formats.nativeElement.scrollTo({ left: moveCalc, behavior: 'smooth' });
    this.cdr.detectChanges();

    this.showFowardContainer = moveCalc + this.offset * 2 < this.formats.nativeElement.scrollWidth;
    this.showNext = false;

    // If clicked next, then back button is always there
    this.showBackContainer = true;
    this.cdr.detectChanges();
  }

  showFowardIcon() {
    this.calculateTopPosition();
    this.showNext = true;
    this.cdr.detectChanges();
  }

  hideFowardIcon() {
    this.showNext = false;
    this.cdr.detectChanges();
  }

  showBackIcon() {
    this.calculateTopPosition();
    this.showBack = true;
    this.cdr.detectChanges();
  }

  hideBackIcon() {
    this.showBack = false;
    this.cdr.detectChanges();
  }

  productDetails(id: number, ean: string) {
    const param = id ? id + '' : ean;
    this.selectedFormatId = param;
    const currentRoute = `product/details/${param}`;
    this.store.dispatch(new ChangeCurrentRoute(currentRoute));
    if (id) {
      this.router.navigate([currentRoute]);
    } else {
      this.router.navigate([currentRoute], { queryParams: { type: 'ean' } });
    }
  }

  public calculateTopPosition() {
    const detailsElement = document.getElementById('product-detail-container');
    const pos = this.formats.nativeElement.offsetTop - detailsElement.scrollTop - 8;
    this.topPosition = pos;
  }

  @HostListener('window:scroll', ['$event'])
  scrollHandler(event) {
    if (this.formats.nativeElement.scrollLeft > 0) {
      this.showBackContainer = true;
    } else {
      this.showBackContainer = false;
    }
    this.showFowardContainer = this.formats.nativeElement.scrollLeft + this.offset * 2 < this.formats.nativeElement.scrollWidth;
  }

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