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';
import { LoadingController } from '@ionic/angular';
import { AlertController } from '@ionic/angular';

@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 = '';
    selectedFoodType: string = '';
    loader: any;

    constructor(
        private mallService: MallService,
        private router: Router,
        private toastService: ToastService,
        public loadingController: LoadingController,
        public alertController: AlertController
    ) { }

    async presentLoading() {
        this.loader = await this.loadingController.create({
            message: 'Please wait...',
            spinner: 'dots',
            mode: 'ios'
        });
        await this.loader.present();
    }

    async presentAlert(message: string) {
        const alert = await this.alertController.create({
            message: message,
            mode: 'ios',
            buttons: ['OK']
        });

        await alert.present();
    }

    getMallsByFoodType(type: string) {
        this.selectedFoodType = type;
        this.mallService.mallsByTypes(type).then((response: Array<any>) => {
            if (response.length > 0) {
                this.allMalls = response;
                this.tempMalls = response;
            } else {
                this.toastService.presentToast("No Malls of the type " + this.selectedFoodType);
                this.allMalls = [];
                this.tempMalls = [];
            }
        }, () => {
            this.toastService.presentToast("Failed to get malls of this food type", "warning");
        });
    }

    ngOnInit() {
        this.getMallsByLocation();
    }

    toggleMallBookmark(mallData: any) {
        mallData.mall.is_bookmarked = !mallData.mall.is_bookmarked;
        this.mallService.updateMallData(mallData);
    }

    doRefresh(e: any) {
        this.selectedFoodType = '';
        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);
        }
    }

    getMallsByLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition((position) => {
                this.presentLoading();
                this.mallService.mallsByLocation(position.coords.latitude, position.coords.longitude).then((response: any) => {
                    if (response.length > 0) {
                        this.allMalls = response;
                        this.tempMalls = response;
                        this.loader ? this.loader.dismiss() : null;
                    } else {
                        this.toastService.presentToast("No malls near you your location, Getting all the malls...", "warning");
                        this.getAllMalls();
                    }
                }, () => {
                    this.loader ? this.loader.dismiss() : null;
                    this.toastService.presentToast("Failed to fetch malls for your location", "danger");
                });
            }, () => {
                this.loader ? this.loader.dismiss() : null;
                this.toastService.presentToast("Location access is mandatory", "danger");
                this.presentAlert("Settings > Site Settings > Location > Blocked > Change permission");
                // this.getAllMalls();
            });
        } else {
            this.presentLoading();
            this.getAllMalls();
        }
    }

    getAllMalls() {
        this.mallService.allMalls().then((response) => {
            this.allMalls = response;
            localStorage.setItem("malls", JSON.stringify(this.allMalls))
            this.tempMalls = response;
            this.loader ? this.loader.dismiss() : null;
        }, (error) => {
            this.loader ? this.loader.dismiss() : null;
            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;
        }
    }

}
