import { Component, OnInit, ViewChild } from '@angular/core';
import { IonSlides } from '@ionic/angular';
import { Location } from '@angular/common';
import { Router, ActivatedRoute } from '@angular/router';
import { CartsService } from './../../config/cart.service';
import { OrdersService } from './../../config/order.service';
import { ModalController } from '@ionic/angular';
import { DeliverypopPage } from '../deliverypop/deliverypop.page';


@Component({
  selector: 'app-cart',
  templateUrl: './cart.page.html',
  styleUrls: ['./cart.page.scss'],
})
export class CartPage implements OnInit {

  @ViewChild(IonSlides, { static: false }) slides: IonSlides;
  currentIndex: any;
  count: any;
  gateway: any;
  loader = false;
  cartwizard = {
    initialSlide: 0,
    speed: 1000,
    allowTouchMove: false
  };

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private location: Location,
    public cartService: CartsService,
    public orderService: OrdersService,
    public modalController: ModalController
  ) {

    this.currentIndex = 0;
    this.count = 1;
    this.gateway = 1;
    this.cartService.cartList();
  }

  ngOnInit() {
  }

  getwaypaypal() {
    this.gateway = 1;
  }

  getwayafterpay() {
    this.gateway = 2;
  }

  getwaypayk() {
    this.gateway = 3;
  }

  async finishpop() {
    const modal = await this.modalController.create({
      component: DeliverypopPage
    });
    return await modal.present();
  }



  goToPage(path, data = null) {
    this.router.navigateByUrl(path, { queryParams: data });
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  }

  goBack() {
    this.location.back();
  }



  next(index: number = null) {
    this.loader = true;
    const This = this;
    setTimeout(() => {
      This.loader = false;
    }, 500);
    console.log(index);
    if (index === 2) {
      const state = this.orderService.checkOut(this.cartService.carts).then((data) => {
        console.log('ready for slide');
        this.slides.slideNext();
      });
    } else {
      this.slides.slideNext();
    }
  }

  prev() {
    this.slides.slidePrev();
  }

  addCount() {
    // this.count = this.count+1
  }

  removeCount() {
    // this.count = this.count - 1;
    if (this.count < 0) {
      this.count = 0;
    }
  }


  slideChanged() {
    this.slides.getActiveIndex().then(index => {
      this.currentIndex = index;
      console.log(this.currentIndex);
    });
  }

  sliderChange() {
    this.orderService.checkout.subscribe(state => {
      if (state) {
        this.next();
        this.orderService.checkout.next(false);
      }
    });
  }

}
