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';
import { ServiceService } from './../../config/service.service';
import { AddressService } from './../../config/address.service';
import { AddressList } from './../../config/services/address'
import { zip } from 'rxjs';


@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;
  custId: any;
  custAddress: AddressList;
  cartwizard = {
    initialSlide: 0,
    speed: 1000,
    allowTouchMove: false
  };
  deliveryCharge: number;
  taxAmount: number;
  discountApplied: boolean;
  discount: number;
  totalAmt: number;

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

    this.currentIndex = 0;
    this.count = 1;
    this.gateway = 1;
    this.deliveryCharge = 0;
    this.taxAmount = 0;
    this.discountApplied = false;
    this.discount = 0;
    this.cartService.cartList();
    const users = this.service.get('user').then((data) => {
      if (data) {
        data = JSON.parse(data);
        this.custId = data.uid;
        this.addressService.addList(data.uid);
      }
    });

  }

  ngOnInit() {
    let address = this.addressService.addressList.find(x => x.defaultVal === 1);
    if (!address) {
      address = this.addressService.addressList[0];
    }
    this.custAddress = address;
    console.log(address);
  }

  getwaypaypal() {
    this.gateway = 1;
  }

  getwayafterpay() {
    this.gateway = 2;
  }

  getDeliveryCharge(amount) {
    if (amount >= 150) {
      this.deliveryCharge = 0;
    } else {
      this.deliveryCharge = 10;
    }
    return this.deliveryCharge;
  }

  getTax(amount) {
    return this.taxAmount = (amount * 10) / 100;
  }

  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 otherCharges = {
        deliveryCharge : this.deliveryCharge,
        taxAmount: this.taxAmount,
        discount: this.discount,
        discountApplied: this.discountApplied,
        totalAmt: this.totalAmt,
        custAddress: this.custAddress
      }; 
      const state = this.orderService.checkOut(this.cartService.carts, otherCharges).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);
      }
    });
  }

  getTotal(total) {
    const actualTotal = (this.deliveryCharge + this.taxAmount + total) - this.discount;
    this.totalAmt = actualTotal;
    return actualTotal;
  }

  promoApply(code) {
    console.log(code);
    this.cartService.checkPromo(code).subscribe((value) => {
      if (value.length > 0) {
        const promo = value[0];
        this.discountApplied = true;
        if (value[0].type === 1) {
          const rate = value[0].amount;
          const upto = value[0].amount;
          const percentage = (this.cartService.cartTotal * rate) / 100;
          this.discount = percentage > upto ? upto : percentage;
        } else {
          this.discount = value[0].amount;
        }
      }
    });
  }

}
