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;
  deliveryTime: any;
  cartwizard = {
    initialSlide: 0,
    speed: 1000,
    allowTouchMove: false
  };
  deliveryCharge: number;
  taxAmount: number;
  discountApplied: boolean;
  discount: number;
  totalAmt: number;
  bookDate: any;
  timeinterval: any;
  paymentMethod: 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
  ) {
    console.log('cart loaded');
    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.paymentMethod = 'PayPal';
    // 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.service.get('cartCenter').then((centerData) => {
          this.addressService.defaultAddress(this.custId);
          this.addressService.getNearBy(centerData, this.custId);
        }); */
      }
    });
    setTimeout(() => {
      this.loader = false;
    }, 1000);
  }

  ngOnInit() {
    /* const This = this;
    console.log(this.addressService.nearestList);
    setTimeout(() => {
      this.setAddress();
    }, 1000); */

  }

  ionViewWillEnter() {
    const users = this.service.get('user').then(data => {
      if (data) {
        data = JSON.parse(data);
        const This = this;
        this.cartService.cartList(data.uid);
        setTimeout(() => {
          if (this.cartService.carts.length > 0) {
            const cart = this.cartService.carts[0];
          }
        }, 1000);
      }
    });
  }

  getwaypaypal() {
    this.gateway = 1;
    this.paymentMethod = 'PayPal';
  }

  getwayafterpay() {
    this.gateway = 2;
    this.paymentMethod = 'AfterPay';
  }

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

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

  getwaypayk() {
    this.gateway = 3;
    this.paymentMethod = 'PayK';
  }

  getwaycod() {
    this.gateway = 4;
    this.paymentMethod = 'COD';
  }

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

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

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

  setDefault(addressId: any, index: number) {
    console.log('loading....');
    this.loader = true;
    this.addressService.custAddress = this.addressService.nearestList[index];
    console.log(this.custAddress);
    this.istoggle();
    setTimeout(() => {
      this.loader = false;
    }, 1000);
  }

  next(index: number = null) {
    this.loader = true;
    const This = this;
    setTimeout(() => {
      This.loader = false;
    }, 500);
    console.log(index);
    if (index === 2) {
      if (this.addressService.custAddress !== undefined) {
        const otherCharges = {
          deliveryCharge: this.deliveryCharge,
          taxAmount: this.taxAmount,
          discount: this.discount,
          discountApplied: this.discountApplied,
          totalAmt: this.totalAmt,
          custAddress: this.addressService.custAddress,
          paymentMethod: this.paymentMethod
        };
        const state = this.orderService
          .checkOut(this.cartService.carts, otherCharges, this.addressService.centerLoc)
          .then(data => {
            this.cartService.cartCenter = '';
            const cartCount = this.orderService.cartCount;
            const timer = ((cartCount - 1) * 20) + 60;
            const totalTime = this.add_minutes(timer);
            console.log('ready for slide');
            this.timeinterval = setInterval(() => {
              This.getDeliveryTime(totalTime.getTime());
            }, 1000);
            this.slides.slideNext();
          });
      } else {
        alert('Please choose delivery location');
      }
    } else {
      this.slides.slideNext();
    }
  }

  add_minutes(minutes) {
    const dt = new Date();
    return new Date(dt.getTime() + minutes * 60000);
  }

  getDeliveryTime(timeStamp) {
    const endDate = new Date(timeStamp);
    endDate.setHours(endDate.getHours());
    const t = this.getTimeRemaining(endDate, new Date());
    const minutes = t.minutes < 10 ? '0' + t.minutes : t.minutes;
    const seconds = t.seconds < 10 ? '0' + t.seconds : t.seconds;
    const hours = t.hours < 10 ? '0' + t.hours : t.hours;
    this.deliveryTime = hours + ' : ' + minutes + ' : ' + seconds;
    if (t.t <= 0) {
      clearInterval(this.timeinterval);
    }
  }

  getTimeRemaining(endtime, currDate) {
    const t = Date.parse(endtime) - Date.parse(currDate);
    const hours = Math.floor((((t / 1000) / 60) / 60) % 60);
    const seconds = Math.floor((t / 1000) % 60);
    const minutes = Math.floor((t / 1000 / 60) % 60);
    return {
      t,
      hours,
      minutes,
      seconds
    };
  }

  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.toFixed(2);
  }

  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 = Math.round((this.cartService.cartTotal * rate) / 100).toFixed(2);
          this.discount = percentage > upto ? upto : percentage;
        } else {
          this.discount = value[0].amount;
        }
        this.discount.toFixed(2);
      }
    });
  }

  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
    );
  }

  unEscape(text: string) {
    const regex = '%uFFFD';
    return unescape(text.replace(/%uFFFD/g, ''));
  }
}
