import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';
import { MallService } from '../services/mall.service';
import { IMall } from '../models/mall';
import CartItem from '../models/cart-item';
import { IOutlet } from '../models/outlet';
import MenuItem from '../models/menu-item';
import { CartItemService } from '../services/cart-item.service';

@Component({
    selector: 'app-outlet-details',
    templateUrl: './outlet-details.page.html',
    styleUrls: ['./outlet-details.page.scss'],
})
export class OutletDetailsPage implements OnInit {
    mall_details: IMall;
    outlet_details: IOutlet;
    temp_outlet_details: IOutlet;
    show_top_bar: boolean = false;
    show_only_veg: boolean = false;
    selected_tag: string = null;
    selected_description: string = null;
    show_sort_popup: boolean = false;
    selected_sort: string = null;
    cart_items: Array<CartItem> = [];
	show_grid: boolean = true;
	show_filter_popup: boolean = false;

    constructor(
        private route: ActivatedRoute,
		private router: Router,
        private location: Location,
        private mallService: MallService,
        private cartService: CartItemService
    ) { }

    ngOnInit() {

    }

	ionViewDidEnter() {
		let mall_id = this.route.snapshot.paramMap.get('mall_id');
        let outlet_id = this.route.snapshot.paramMap.get('outlet_id');

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

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

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

    addToCart(item: MenuItem) {
        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);
    }

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


    increaseCartItemCount(item: MenuItem) {
        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);
    }

    decreaseCartItemCount(item: MenuItem) {
        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);
    }

    onScroll(event: any) {
        if (event.detail.scrollTop > 100) {
            this.show_top_bar = true;
        } else {
            this.show_top_bar = false;
        }
    }

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

    toggleBookmark() {
        this.outlet_details.is_bookmarked = !this.outlet_details.is_bookmarked;
    }


    filterByTag(tag: string) {
        if (this.selected_tag === tag) {
            this.selected_tag = null;
            this.temp_outlet_details.menu_items = JSON.parse(JSON.stringify(this.outlet_details.menu_items));
        } else {
            this.selected_tag = tag;
            let menu_items: Array<MenuItem> = [];
            for (let i = 0; i < this.outlet_details.menu_items.length; i += 1) {
                if (this.outlet_details.menu_items[i].tags.includes(tag)) {
                    menu_items.push(this.outlet_details.menu_items[i]);
                }
            }
            this.temp_outlet_details.menu_items = menu_items;
        }
    }

    sortBy(type: string) {
        this.selected_sort = type;
        switch(this.selected_sort) {
            case 'name': this.temp_outlet_details.menu_items.sort(function(a, b){
                if(a.name < b.name) { return -1; }
                if(a.name > b.name) { return 1; }
                return 0;
            });
            break;
            case 'rating': this.temp_outlet_details.menu_items.sort(function(a, b){
                if(a.rating < b.rating) { return -1; }
                if(a.rating > b.rating) { return 1; }
                return 0;
            }).reverse();
            break;
            case 'price': this.temp_outlet_details.menu_items.sort(function(a, b){
                if(a.price < b.price) { return -1; }
                if(a.price > b.price) { return 1; }
                return 0;
            });
            break;
            case 'duration': this.temp_outlet_details.menu_items.sort(function(a, b){
                if(a.wait_duration < b.wait_duration) { return -1; }
                if(a.wait_duration > b.wait_duration) { return 1; }
                return 0;
            });
            break;
        }
    }

	goToCart() {
		this.router.navigate(['/cart']);
	}

}
