import { Component, ViewChild, OnInit } from '@angular/core';
import { IonSlides } from '@ionic/angular';
import 'web-animations-js/web-animations.min';
import { toLeft } from '../animations/toLeftAndBack';
import { toRight } from '../animations/toRightAndBack';
import { fadeIn } from '../animations/fade-in';
import { Router } from '@angular/router';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
  animations: [toLeft, toRight, fadeIn]
})
export class HomePage implements OnInit {
  @ViewChild(IonSlides) slides;
  options = {
    speed: 1000,
    allowTouchMove: false
  };
  index;
  active = [true, false, false, false];
  startX;
  startY;
  X;
  Y;
  toLeft = 'backLeft';
  toRight = 'backRight';

  constructor(private router: Router) {}

  ngOnInit() {
    document.getElementById('slideComponent').addEventListener('touchstart', <TouchEvent>(e) => {
      this.startX = e.touches[0].pageX;
      this.startY = e.touches[0].pageY;
    });
    document.getElementById('slideComponent').addEventListener('touchmove', <TouchEvent>(e) => {
      const moveEndX = e.touches[0].pageX;
      const moveEndY = e.touches[0].pageY;
      this.X = moveEndX - this.startX;
      this.Y = moveEndY - this.startY;
    });
    document.getElementById('slideComponent').addEventListener('touchend', <TouchEvent>(e) => {
      if ( this.X > 100 ) {
        this.slidePrev();
      } else if ( this.X < -100 ) {
        this.slideNext();
      }
    });
  }

  slideOnChange() {
    this.slides.getActiveIndex().then((index) => {
      this.changeIndex(index);
    });
  }

  changeIndex(index) {
    const active = [false, false, false, false];
    active[index] = true;
    this.active = active;
  }

  goActive(index) {
    this.changeIndex(index);
    this.slides.slideTo(index, 500);
  }

  slideNext() {
    this.slides.getActiveIndex().then((index) => {
      if (index + 1 < 4) {
        this.goActive((index + 1));
      } else {
        this.atLast();
      }
    });
  }

  slidePrev() {
    this.slides.getActiveIndex().then((index) => {
      if (index - 1 >= 0) {
        this.goActive((index - 1));
      } else {
        this.atFirst();
      }
    });
  }

  atFirst() {
    this.toRight = 'toRight';
    setTimeout(() => {
      this.toRight = 'backRight';
    }, 250);
  }

  atLast() {
    this.toLeft = 'toLeft';
    setTimeout(() => {
      this.toLeft = 'backLeft';
    }, 250);
  }
}
