import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import CartItem from '../models/cart-item';
import { CartItemService } from '../services/cart-item.service';
import { MallService } from '../services/mall.service';
import { IMall } from '../models/mall';
import * as moment from 'moment';
import { Router } from '@angular/router';
import { IOutlet } from '../models/outlet';
import { OrderService } from '../services/order.service';
import { ToastController } from '@ionic/angular';

@Component({
    selector: 'app-cart',
    templateUrl: './cart.page.html',
    styleUrls: ['./cart.page.scss'],
})
export class CartPage implements OnInit {
    show_order_details: boolean = false;
    cart_items: any = [];
    all_malls: Array<IMall> = [];
    total_cart_amount: number = 0;
    show_promocodes: boolean = false;
	selected_promocode: string = '';
	total_savings: number = 0;
	temp_outlet_details: IOutlet;
	instant_menu: boolean = false;
	mall_details: IMall;
    outlet_details: IOutlet;
	new_pickup_time: Date;
	cart_outlets: any = [];

    constructor(
        private location: Location,
        private cartService: CartItemService,
        private mallService: MallService,
        private router: Router,
		private orderService: OrderService,
		public toastController: ToastController
    ) { }

    ngOnInit() {}

    ionViewDidEnter() {
		document.querySelector('.menu-icon-holder').classList.add('hide');
		this.refresh();
    }

	refresh() {
		this.show_order_details = false;
	    this.cart_items = [];
	    this.all_malls= [];
	    this.total_cart_amount = 0;

        this.mallService.getAllMalls().then((malls: Array<IMall>) => {
            this.all_malls = malls;
        });

        this.cartService.getAllCartItems().then((cart_items: Array<CartItem>) => {
            this.cart_items = cart_items;

            let i: number;

            for (i = 0; i < this.cart_items.length; i += 1) {
                let mall = this.all_malls.find(mall => mall.id === this.cart_items[i].mall_id);
                let outlet = mall.outlets.find(outlet => outlet.id === this.cart_items[i].outlet_id);
                this.cart_items[i].menu_details = outlet.menu_items.find(item => item.id === this.cart_items[i].menu_item);
                this.total_cart_amount += this.cart_items[i].total_price;

				if (this.cart_outlets.filter((cart_outlet: any) => cart_outlet.id === this.cart_items[i].outlet_id).length === 0) {
					this.cart_outlets.push({id: this.cart_items[i].outlet_id, name: outlet.name});
				}
            }

			console.log(this.cart_outlets);
        });
	}

	isMaxDeliveryTime(outlet_id: string) {
		let pricing = this.cart_items.filter((item => item.outlet_id === outlet_id));
		if (pricing.length > 0) {
			let max = pricing.reduce((prev, current) => {
				return (prev.pickup_time > current.pickup_time) ? prev : current
			});
			return max;
		} else {
			return 0;
		}

	}

	openInstantMenu(item: any) {
		this.instant_menu = true;
		this.mallService.getMallByID(item.mall_id).then((data: IMall) => {
            this.mall_details = data;
            this.outlet_details = this.mall_details.outlets.find((outlet) => outlet.id === item.outlet_id);
            this.temp_outlet_details = JSON.parse(JSON.stringify(this.outlet_details));
        });
	}

	ngOnDestroy() {
		document.querySelector('.menu-icon-holder').classList.remove('hide');
	}

    increaseCartItemCount(item: any) {
        let i: number, cart_items: any;
        for (i = 0; i < this.cart_items.length; i += 1) {
            if (this.cart_items[i].menu_item === item.menu_item) {
                this.cart_items[i].quantity += 1;
                this.cart_items[i].total_price = this.calculateDiscount(item.menu_details.price, item.menu_details.discount) * this.cart_items[i].quantity;
                this.total_cart_amount = this.total_cart_amount + this.calculateDiscount(item.menu_details.price, item.menu_details.discount);
            }
        }
        cart_items = JSON.parse(JSON.stringify(this.cart_items));
        for (i = 0; i < cart_items.length; i += 1) {
            delete cart_items[i]['menu_details'];
        }
		this.calculateTotalAfterPromo();
        this.cartService.updateCartItems(cart_items);
    }

    decreaseCartItemCount(item: any) {
        let i: number, cart_items : any;
        for (i = 0; i < this.cart_items.length; i += 1) {
            if (this.cart_items[i].menu_item === item.menu_item) {
                this.cart_items[i].quantity -= 1;
                this.cart_items[i].total_price = this.calculateDiscount(item.menu_details.price, item.menu_details.discount) * this.cart_items[i].quantity;
                this.total_cart_amount = this.total_cart_amount - this.calculateDiscount(item.menu_details.price, item.menu_details.discount);
                if (this.cart_items[i].quantity === 0) {
                    this.cart_items.splice(i, 1);
                }
            }
        }
        cart_items = JSON.parse(JSON.stringify(this.cart_items));
        for (i = 0; i < cart_items.length; i += 1) {
            delete cart_items[i]['menu_details'];
        }
		this.calculateTotalAfterPromo();
        this.cartService.updateCartItems(cart_items);
    }

    getPickupTimeFormat(date: Date) {
        return moment(date).calendar();
    }

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

    goToOutlet(mall_id: string, outlet_id: string) {
        this.router.navigate(['/outlet-details', { mall_id: mall_id, outlet_id: outlet_id }]);
    }

    calculateDiscount(price: number, discount: number) {
        return price - (price * discount / 100);
    }

	calculateTotalAfterPromo() {
		switch(this.selected_promocode) {
			case 'SAVE100':
			if (this.total_cart_amount > 100) {
				this.total_cart_amount = this.total_cart_amount - 100;
				this.total_savings = 100;
			}
			break;
			case 'SAVE10PER': this.total_cart_amount = this.total_cart_amount - ((this.total_cart_amount * 10) / 100);
			this.total_savings = (this.total_cart_amount * 10) / 100;
			break;
		}
	}

	removePromocode() {
		this.total_savings = 0;
		this.total_cart_amount = 0;
		this.selected_promocode = '';
		let i: number;

		for (i = 0; i < this.cart_items.length; i += 1) {
			let mall = this.all_malls.find(mall => mall.id === this.cart_items[i].mall_id);
			let outlet = mall.outlets.find(outlet => outlet.id === this.cart_items[i].outlet_id);
			this.cart_items[i].menu_details = outlet.menu_items.find(item => item.id === this.cart_items[i].menu_item);
			this.total_cart_amount += this.cart_items[i].total_price;
		}
	}

	checkIfPresentInCart(id: string) {
        let i: number;
        for (i = 0; i < this.cart_items.length; i += 1) {
            if (this.cart_items[i].menu_item === id) {
                return true;
            }
        }
        return false;
    }

	getItemCount(id: string) {
        let i: number;
        for (i = 0; i < this.cart_items.length; i += 1) {
            if (this.cart_items[i].menu_item === id) {
                return this.cart_items[i].quantity;
            }
        }
        return 0;
    }


	addToCart(item: any) {
        this.cart_items.push({
            menu_item: item.id,
            quantity: 1,
            pickup_time: new Date(new Date().setMinutes(new Date().getMinutes() + item.wait_duration)),
            outlet_id: this.outlet_details.id,
            mall_id: this.mall_details.id,
            take_away: true,
            total_price: this.calculateDiscount(item.price, item.discount)
        });

        this.cartService.updateCartItems(this.cart_items).then(() => {
			this.refresh();
		});
    }

	decreaseInstantCartItemCount(item: any) {
        let i: number;
        for (i = 0; i < this.cart_items.length; i += 1) {
            if (this.cart_items[i].menu_item === item.id) {
                this.cart_items[i].quantity -= 1;
                this.cart_items[i].total_price = this.calculateDiscount(item.price, item.discount) * this.cart_items[i].quantity;
                if (this.cart_items[i].quantity === 0) {
                    this.cart_items.splice(i, 1);
                }
            }
        }
        this.cartService.updateCartItems(this.cart_items);
    }

	increaseInstantCartItemCount(item: any) {
        let i: number;
        for (i = 0; i < this.cart_items.length; i += 1) {
            if (this.cart_items[i].menu_item === item.id) {
                this.cart_items[i].quantity += 1;
                this.cart_items[i].total_price = this.calculateDiscount(item.price, item.discount) * this.cart_items[i].quantity;
            }
        }
        this.cartService.updateCartItems(this.cart_items);
    }

	placeOrder() {
		let calculated_total = (this.total_cart_amount + 20) + ((this.total_cart_amount + 20) * (18 / 100));
		this.orderService.createOrder(this.cart_items, calculated_total, this.selected_promocode).then(() => {
			this.presentToast('Order has been created! :-)', 'dark');
			this.cartService.clearCartItems();
			document.querySelector('.menu-icon-holder').classList.remove('hide');
			this.router.navigate(['/profile']);
		}, () => {
			this.presentToast('Failed to create the order, We\'re sorry for the inconvenience', 'danger');
		});
	}

	async presentToast(text: string, color: string) {
		const toast = await this.toastController.create({
			message: text,
			position: 'bottom',
			duration: 4000,
			color: color,
			buttons: [
				{
					text: 'Done',
				}
			]
		});
		toast.present();
	}

}
