import { Component, OnInit, ViewChild,ElementRef } from '@angular/core';
import { MallService } from '../services/mall.service';
import { ToastService } from '../services/toast.service';
import { Router } from '@angular/router';

@Component({
    selector: 'app-malls',
    templateUrl: './malls.page.html',
    styleUrls: ['./malls.page.scss'],
})
export class MallsPage implements OnInit {
    @ViewChild('searchbar', null) searchElement: ElementRef;
    selected_tab: string = 'you';
    tempMalls: any = [];
    allMalls: any = [];
    show_sort_popup: boolean = false;
    showSearchBar: boolean = false;
    selected_sort: string = null;
    searchTerm: string = '';

    constructor(
        private mallService: MallService,
        private router: Router,
        private toastService: ToastService
    ) { }

    ngOnInit() {
        this.getMallsByLocation();
        this.getMallsByFoodType('pizza');
    }

    toggleMallBookmark(index: number) {
        this.tempMalls[index].mall.is_bookmarked = !this.tempMalls[index].mall.is_bookmarked;
        this.allMalls[index].mall.is_bookmarked = !this.allMalls[index].mall.is_bookmarked;
        localStorage.allMalls = JSON.stringify(this.allMalls);
        this.mallService.updateMallData(this.tempMalls[index]);
    }

    doRefresh(e: any) {
        this.getMallsByLocation();
        e.target.complete();
    }

    toggleSearchBar() {
		if (this.searchTerm.length > 0) {
			this.searchTerm = '';
			this.tempMalls = JSON.parse(JSON.stringify(this.allMalls));
		} else {
			this.showSearchBar = !this.showSearchBar;
	        setTimeout(()=>{ // this will make the execution after the above boolean has changed
	            this.searchElement.nativeElement.focus();
	        }, 1);
		}
    }

    searchAllMalls() {
        if (this.searchTerm.trim().length > 0) {
            this.tempMalls = this.allMalls.filter((mallData: any) => {
                return mallData.mall.mall_name.toLowerCase().includes(this.searchTerm.toLowerCase());
            });
        } else {
            this.tempMalls = JSON.parse(JSON.stringify(this.allMalls));
        }
    }

    shareMallDetails(mallData) {
        if (window.navigator && window.navigator['share']) {
            const shareData = {
                title: mallData.mall.mall_name,
                text: mallData.mall.description,
                url: 'https://maps.google.com/?q=' + mallData.latitude + ',' + mallData.longitude
            }

            window.navigator['share'](shareData);
        }
    }

    getMallsByFoodType(type: string) {
        this.mallService.mallsByTypes(type).then((data) => {
            console.log(data);
        });
    }

    getMallsByLocation() {
        if (navigator.geolocation) {
            this.toastService.presentToast("Getting malls based on your location...", "dark");
            navigator.geolocation.getCurrentPosition((position) => {
                this.mallService.mallsByLocation(position.coords.latitude, position.coords.longitude).then((response: any) => {
                    if (response.length > 0) {
                        localStorage.allMalls = JSON.stringify(response);
                        this.allMalls = JSON.parse(localStorage.allMalls);
                        this.tempMalls = JSON.parse(localStorage.allMalls);
                    } else {
                        this.toastService.presentToast("No malls near you your location, Getting all the malls...", "warning");
                        this.getAllMalls();
                    }
                }, () => {
                    this.toastService.presentToast("Failed to fetch malls for your location", "danger");
                });
            });
        } else {
            this.getAllMalls();
        }
    }

    getAllMalls() {
        this.mallService.allMalls().then((response) => {
            localStorage.allMalls = JSON.stringify(response);
            this.allMalls = JSON.parse(localStorage.allMalls);
            this.tempMalls = JSON.parse(localStorage.allMalls);
        }, (error) => {
            console.log(error);
        });
    }

    showMallDetails(mall: any) {
        this.router.navigate(['/mall-details', { mall: JSON.stringify(mall) }]);
    }

    sortBy(type: string) {
        this.selected_sort = type;
        switch(this.selected_sort) {
            case 'name': this.tempMalls.sort(function(a: any, b: any){
                if(a.mall.mall_name < b.mall.mall_name) { return -1; }
                if(a.mall.mall_name > b.mall.mall_name) { return 1; }
                return 0;
            });
            break;
            case 'rating': this.tempMalls.sort(function(a: any, b: any){
                if(a.mall.rating < b.mall.rating) { return -1; }
                if(a.mall.rating > b.mall.rating) { return 1; }
                return 0;
            }).reverse();
            break;
        }
    }

}
