import { Component, OnInit, ViewChild,ElementRef } from '@angular/core';
import { MallService } from '../services/mall.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
    ) { }

    ngOnInit() {
        this.storeAllMalls();
    }

    toggleSearchBar() {
        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((mall: any) => {
                return mall.mall_name.toLowerCase().includes(this.searchTerm.toLowerCase());
            });
        } else {
            this.tempMalls = JSON.parse(JSON.stringify(this.allMalls));
        }
    }

    storeAllMalls() {
        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_name < b.mall_name) { return -1; }
                if(a.mall_name > b.mall_name) { return 1; }
                return 0;
            });
            break;
            case 'rating': this.tempMalls.sort(function(a: any, b: any){
                if(a.rating < b.rating) { return -1; }
                if(a.rating > b.rating) { return 1; }
                return 0;
            }).reverse();
            break;
        }
    }

}
