import { Component, ViewChild, OnInit } from '@angular/core';
import { IonSlides } from '@ionic/angular';

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

  ngOnInit() {
    document.getElementById('slideComponent').addEventListener('touchstart', <TouchEvent>(e) => {
      e.preventDefault();
      this.startX = e.touches[0].pageX;
      this.startY = e.touches[0].pageY;
    });
    document.getElementById('slideComponent').addEventListener('touchmove', <TouchEvent>(e) => {
      e.preventDefault();
      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) => {
      e.preventDefault();
      if ( this.X > 0 ) {
        this.slidePrev();
      } else if ( this.X < 0 ) {
        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));
      }
    });
  }

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