import * as tslib_1 from "tslib";
import { Component, 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 { trigger, transition, animate, style } from '@angular/animations';
import { Events } from '@ionic/angular';
let CartPage = class CartPage {
    constructor(router, route, location, cartService, orderService, modalController, service, addressService, event) {
        this.router = router;
        this.route = route;
        this.location = location;
        this.cartService = cartService;
        this.orderService = orderService;
        this.modalController = modalController;
        this.service = service;
        this.addressService = addressService;
        this.event = event;
        this.isShow = false;
        this.loader = false;
        this.cartwizard = {
            initialSlide: 0,
            speed: 1000,
            allowTouchMove: false
        };
        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 = 0;
        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);
        this.setCurrentLocation();
    }
    ngOnInit() {
        /* const This = this;
        console.log(this.addressService.nearestList);
        setTimeout(() => {
          this.setAddress();
        }, 1000); */
    }
    setCurrentLocation() {
        const This = this;
        if ('geolocation' in navigator) {
            navigator.geolocation.getCurrentPosition(position => {
                this.lat = position.coords.latitude;
                this.lng = position.coords.longitude;
            });
        }
    }
    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';
    }
    finishpop() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const modal = yield this.modalController.create({
                component: DeliverypopPage
            });
            return yield modal.present();
        });
    }
    goToPage(path, data = null) {
        if (path === 'nearby') {
            this.addressService.addressState = 1;
        }
        this.router.navigateByUrl(path, { queryParams: data, replaceUrl: true });
        document.body.scrollTop = document.documentElement.scrollTop = 0;
    }
    goBack() {
        this.event.publish('home');
        this.location.back();
    }
    setDefault(addressId, index) {
        console.log('loading....');
        this.loader = true;
        this.addressService.custAddress = this.addressService.addressList[index];
        console.log(this.custAddress);
        this.istoggle();
        setTimeout(() => {
            this.loader = false;
        }, 1000);
    }
    next(index = null) {
        this.loader = true;
        const This = this;
        setTimeout(() => {
            This.loader = false;
        }, 500);
        console.log(index);
        if (index === 2) {
            if (this.addressService.custAddress !== undefined) {
                if (this.addressService.custAddress.nearest === true) {
                    const otherCharges = {
                        deliveryCharge: this.deliveryCharge,
                        taxAmount: this.taxAmount,
                        discount: this.discount,
                        discountApplied: this.discountApplied === 1 ? true : false,
                        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 {
                    this.service.showToast('Not delivered to the selected location', 'top', 'my-error', 1000);
                }
            }
            else {
                this.istoggle();
            }
        }
        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 = 1;
                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);
            }
            else {
                this.discountApplied = 0;
                this.discount = 0;
            }
        });
    }
    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) {
        const regex = '%uFFFD';
        return unescape(text.replace(/%uFFFD/g, ''));
    }
};
tslib_1.__decorate([
    ViewChild(IonSlides, { static: false }),
    tslib_1.__metadata("design:type", IonSlides)
], CartPage.prototype, "slides", void 0);
CartPage = tslib_1.__decorate([
    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%)' }))
                ])
            ])
        ]
    }),
    tslib_1.__metadata("design:paramtypes", [Router,
        ActivatedRoute,
        Location,
        CartsService,
        OrdersService,
        ModalController,
        ServiceService,
        AddressService,
        Events])
], CartPage);
export { CartPage };
//# sourceMappingURL=cart.page.js.map