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 { trigger, transition, animate, style } from '@angular/animations';
import { zip } from 'rxjs';

@Component({
  selector: 'app-cart',
  templateUrl: './cart.page.html',
  styleUrls: ['./cart.page.scss'],
  animations: [
    trigger('slideInOut', [
      transition(':enter', [
        style({ transform: 'translateY(100%)' }),
        animate('200ms ease-in', style({ transform: 'translateY(0%)' }))
      ]),
      transition(':leave', [
        animate('200ms ease-out', style({ transform: 'translateY(100%)' }))
      ])
    ])
  ]
})
export class CartPage implements OnInit {
  @ViewChild(IonSlides, { static: false }) slides: IonSlides;
  currentIndex: any;
  isShow = false;
  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;
  bookDate: any;

  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.bookDate = this.formatDate();
    this.currentIndex = 0;
    this.count = 1;
    this.gateway = 1;
    this.deliveryCharge = 0;
    this.taxAmount = 0;
    this.discountApplied = false;
    this.discount = 0;
    this.cartService.cartList();
    this.loader = true;
    const users = this.service.get('user').then(data => {
      if (data) {
        data = JSON.parse(data);
        this.custId = data.uid;
        this.addressService.addList(data.uid);
      }
    });
    setTimeout(() => {
      this.loader = false;
    }, 1000);
  }

  ngOnInit() {
    console.log(this.addressService.addressList);
    this.setAddress();
  }

  setAddress() {
    if (this.addressService.addressList.length > 0) {
      let address = this.addressService.addressList.find(
        x => x.defaultVal === 1
      );
      if (!address) {
        address = this.addressService.addressList[0];
      }
      this.custAddress = 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();
  }

  setDefault(addressId: any, index: number) {
    console.log(index);
    this.addressService.setDefaultAddress(addressId, this.custId);
    console.log(this.addressService.addressList[index]);
    this.custAddress = this.addressService.addressList[index];
  }

  next(index: number = null) {
    this.loader = true;
    const This = this;
    setTimeout(() => {
      This.loader = false;
    }, 500);
    console.log(index);
    if (index === 2) {
      if (this.custAddress !== undefined) {
        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 {
        alert('Please choose delivery location');
      }
    } 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;
        }
      }
    });
  }

  istoggle() {
    this.isShow = !this.isShow;
  }

  formatDate() {
    const date = new Date();
    const months = [
      'Jan',
      'Feb',
      'Mar',
      'Apr',
      'May',
      'June',
      'July',
      'Aug',
      'Sep',
      'Oct',
      'Nov',
      'Dec'
    ];
    let hours = date.getHours();
    const minutes = date.getMinutes();
    const ampm = hours >= 12 ? 'PM' : 'AM';
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    const newminutes = minutes < 10 ? '0' + minutes : minutes;
    const strTime = hours + ':' + newminutes + ' ' + ampm;
    return (
      months[date.getMonth()] +
      ' ' +
      date.getDate() +
      ',' +
      date.getFullYear() +
      '  ' +
      strTime
    );
  }
}
