import { Injector, Component, ViewChild, AfterViewInit, HostBinding, ElementRef, OnInit, Directive, HostListener, Input, ViewContainerRef } from "@angular/core";
import { AppComponentBase } from "@shared/common/app-component-base";
import { appModuleAnimation } from "@shared/animations/routerTransition";
import { LocalStorageService } from "@shared/utils/local-storage.service";
import { Router } from "@angular/router";
import * as moment from 'moment';
import { LocatorServiceProxy, ShippingPackageServiceProxy } from "@shared/service-proxies/service-proxies";
// import { Select2OptionData } from 'ng2-select2';
import { MapsAPILoader } from "@agm/core";
import { stringify } from "querystring";
import { Options } from "select2";
import { isNull } from "util";
// import { CreatePostalCodesModalComponent } from "@app/sprintship/contact-management/postal-codes/create-or-edit-postalCode-modal.component";

@Component({

    selector: 'mapFlyOutComponent',
    templateUrl: 'map-flyout.component.html',
    animations: [appModuleAnimation()],
    styleUrls: ['map-flyout.component.less'],

})

export class MapFlyOutComponent extends AppComponentBase implements AfterViewInit{

    @HostBinding('id') id = 'kt_quick_sidebar';
    @HostBinding('class')
    classes = 'kt-quick-panel';
    @HostBinding('attr.mQuickSidebarOffcanvas')

    @HostBinding('style.overflow') styleOverflow: any = 'hidden';

    mQuickSidebarOffcanvas: any;

    exampleData: Array<Options>;
    routeData: Array<Options> = [];
    routeRandColor: Array<any> = [];
    holder: Array<Options> = [];
    options: Options ;
    value: string[];
    current: string;
    
    deliveryCheck: boolean = true;
    pickupCheck: boolean = true;

    @Input() filters: {
        locationFilter: number;
        statusFilter: number;
        typeFilter: number;
        startDate: moment.Moment;
        endDate: moment.Moment;
    } = <any>{};

    @Input() route: Array<any> = [];
    data: any;
    points: any;
    status: Array<any> = [];
    allStatus: boolean;
    @Input() active: number;
    select: Array<any> = [];
    driver: Array<any> = [];
    constructor(
        private viewContainerRef: ViewContainerRef,
        injector:Injector,
        private el: ElementRef,
        private router:Router,
        private _locatorAppService: LocatorServiceProxy
    ){
        super(injector);
    }

    _isOpen: boolean;
    _pinned = false;
    
    ngOnInit(){
        if(this.route[0] != 0){
            
            var color = '';
            var routeID = 0;
                this._locatorAppService.getRouteFilter(moment(this.filters.startDate),moment(this.filters.endDate),this.filters.locationFilter,undefined,undefined,undefined)
                .subscribe((result)=>{
                    
                result.items.forEach(item => {
                    if(routeID != item.routeId && this.routeRandColor[item.routeId] == null){
                        this.routeRandColor[item.routeId] = this.getRandomColor();
                        routeID = item.routeId;
                    }
                    item.color = this.routeRandColor[item.routeId];
                })
                this.driver = [];
                this.data = result.items;
                this.plotRouteMarker();
            });
        }else{
            this.route = [];
        }
    }

    ngAfterViewInit(): void{
        this.mQuickSidebarOffcanvas = new KTOffcanvas(this.el.nativeElement, {
            overlay: true,
            baseClass: 'kt-quick-panel',
            closeBy: 'getting_started_close',
            toggleBy: 'getting_started_toggle'
        });

        this.mQuickSidebarOffcanvas.events.push({
            name: 'afterHide',
            handler: () => {
                if (this._pinned) {
                    this.mQuickSidebarOffcanvas.show();
                } else {
                    this.isOpen = false;
                }
            }
        }, {
                name: 'afterShow',
                handler: () => {
                    this.isOpen = true;
                }
            });
    }
    set pinned(newValue: boolean) {
        if (newValue === this._pinned) {
            return;
        }
        this._pinned = newValue;
    }
    get pinned(): boolean {
        return this._pinned;
    }
    reversePinned(): void {
        this.pinned = !this.pinned;
    }
    set isOpen(newValue: boolean) {
        if (newValue === this._isOpen) {
            return;
        }
        this._isOpen = newValue;
    }
    get isOpen(): boolean {
        return this._isOpen;
    }


    getParentComponent() {
        return this.viewContainerRef[ '_data' ].componentView.component.viewContainerRef[ '_view' ].component
    }

    loadFlyOut(): void{
        this.options = {
            width: '300',
            multiple: true,
            tags: true
        };

        if(this.active == 1){
            this.routeClick();
        }
        
        if(this.active == 2){
            this.fleetClick();
        }

        if(this.active == 3){
            this.driverClick();
        }

    }

    routeClick(){
        
        var color = '';
        var routeID = 0;
        // if(this.active != 1){
        //     this.getParentComponent().markers = [];
        //     this.getParentComponent().latestLog = [];
        //     this.getParentComponent().delmarkers = [];
        //     this.getParentComponent().driverP = [];
        // }
        this.active = 1;
        this._locatorAppService.getRouteFilter(moment(this.filters.startDate),moment(this.filters.endDate),this.filters.locationFilter,undefined,undefined,undefined)
        .subscribe((result)=>{
            
            result.items.forEach(item => {
                if(routeID != item.routeId && this.routeRandColor[item.routeId] == null){
                    this.routeRandColor[item.routeId] = this.getRandomColor();
                    routeID = item.routeId;
                }
                item.color = this.routeRandColor[item.routeId];
            })
            this.driver = [];
            this.data = result.items;
            this.data.map((i)=>{i.zone = i.routeId +'/'+ i.zone});
            console.log(this.data);
        });
    }

    fleetClick(){
        
        // if(this.active != 2){
        //     this.getParentComponent().markers = [];
        //     this.getParentComponent().latestLog = [];
        //     this.getParentComponent().delmarkers = [];
        //     this.getParentComponent().driverP = [];
        // }
        this.active = 2;
        this._locatorAppService.getDriverFilter(moment(this.filters.startDate),moment(this.filters.endDate),this.filters.locationFilter,undefined,undefined,undefined)
        .subscribe((result)=>{
            this.route = [];
            this.data = result.items;
        });
    }

    driverClick(){
        
        // if(this.active != 3){
        //     this.getParentComponent().markers = [];
        //     this.getParentComponent().latestLog = [];
        //     this.getParentComponent().delmarkers = [];
        //     this.getParentComponent().driverP = [];
        // }
        this.active = 3;
        this._locatorAppService.getDriverFilter(moment(this.filters.startDate),moment(this.filters.endDate),this.filters.locationFilter,undefined,undefined,undefined)
        .subscribe((result)=>{
            this.route = [];
            this.data = result.items;
        });
    }

    selectAll() {
        if(this.active == 1){
            this.route = this.data.map(x => x.routeId);
            // this.plotRouteMarker();
        }
        if(this.active == 2){
            this.driver = this.data.map(x => x.userId);
            // this.plotFleetMarker();
        }
        if(this.active == 3){
            this.driver = this.data.map(x => x.userId);
            // this.plotDriverMarker();
        }
    }

    unselectAll() {
        this.route = [];
        this.driver = [];
        this.getParentComponent().markers = [];
        this.getParentComponent().latestLog = [];
        this.getParentComponent().delmarkers = [];
        this.getParentComponent().driverP = [];
    }
    
    clearAll() {
        this.getParentComponent().markers = [];
        this.getParentComponent().latestLog = [];
        this.getParentComponent().delmarkers = [];
        this.getParentComponent().driverP = [];
    }

    plotRouteMarker(){
        var color = '';
        var routeID = '';
        if(this.route.length != 0){
            
            this.spinnerService.show();
            this._locatorAppService.getVehicleDestinationPoints(moment(this.filters.startDate),moment(this.filters.endDate),this.filters.locationFilter,undefined,undefined,this.route)
            .subscribe((result)=>{
                this.points = result.items;
                this.points.forEach(item => {
                    if(this.pickupCheck){
                        this.getParentComponent().markers.push(
                            {
                                lat: item.pickUpLatitude,
                                lng: item.pickUpLongtitude,
                                label: item.orderId+"",
                                draggable: false,
                                // pin: pin,
                                driverName: item.driverName,
                                orderId: item.orderId,
                                eta: moment(item.eta).toString(),
                                color: this.routeRandColor[item.routeId]
                            });
                    }

                    if(this.deliveryCheck){
                        this.getParentComponent().delmarkers.push(
                        {
                            lat: item.deliveryLatitude,
                            lng: item.deliveryLongtitude,
                            label: item.orderId+"",
                            draggable: false,
                            // pin: pin,
                            driverName: item.driverName,
                            orderId: item.orderId,
                            eta: moment(item.eta).toString(),
                            color: this.routeRandColor[item.routeId]
                        });
                    }
                });
               
            this.spinnerService.hide(); 
            })

            this._locatorAppService.getVehicleLatestLocationByRoute(moment(this.filters.startDate),moment(this.filters.endDate),this.filters.locationFilter,undefined,undefined,this.route)
            .subscribe((result)=>{
                this.points = result.items;
                this.points.forEach(item => {
                    this.getParentComponent().latestLog.push(
                        {
                            lat: item.latitude,
                            lng: item.longtitude,
                            label: '',
                            draggable: false,
                            // pin: pin,
                            driverName: item.driverName,
                            orderId: item.orderId,
                            eta: moment(item.timeStamp).toString(),
                            color: item.color
                        });
                });
                
            this.spinnerService.hide();
            })
        }
    }
    
    plotFleetMarker(){
        var color = '';
        if(this.driver.length != 0){
            let user = [];
            let userId = 0;
            this.spinnerService.show();
            this._locatorAppService.getVehicleLatestLocation(moment(this.filters.startDate),moment(this.filters.endDate),this.filters.locationFilter,this.route,undefined,undefined)
            .subscribe((result)=>{
                this.points = result.items;
                this.points.forEach(item => {
                    
                    if(item.userId in user){
                        user[item.userId] = user[item.userId] + 1;
                    }else{
                        user[item.userId] =  1;
                    }

                    this.getParentComponent().latestLog.push(
                        {
                            lat: item.latitude,
                            lng: item.longtitude,
                            label: user[item.userId].toString(),
                            draggable: false,
                            driverName: item.driverName,
                            orderId: item.orderId,
                            eta: moment(item.eta).toString(),
                            color: item.color
                        });
                });
                
            this.spinnerService.hide();
            })
            
        }
    }

    plotDriverMarker(){
        var color = '';
        if(this.driver.length != 0){
            let user = [];
            let userId = 0;
            this.spinnerService.show();
            this._locatorAppService.getVehicleLocationLog(moment(this.filters.startDate),moment(this.filters.endDate),this.filters.locationFilter,this.driver,undefined,undefined)
            .subscribe((result)=>{
                this.points = result.items;
                this.points.forEach(item => {
                    
                    if(item.userId in user){
                        user[item.userId] = user[item.userId] + 1;
                    }else{
                        user[item.userId] =  1;
                    }

                    this.getParentComponent().driverP.push(
                        {
                            lat: item.latitude,
                            lng: item.longtitude,
                            label: user[item.userId].toString(),
                            draggable: false,
                            // pin: pin,
                            driverName: item.driverName,
                            orderId: item.orderId,
                            eta: moment(item.eta).toString(),
                            color: item.color
                        });
                });
                
            this.spinnerService.hide();
            })
        }
    }

    showDelivery(event){
        this.deliveryCheck = event.target.checked;
        // if(this.active == 1){
        //     this.plotRouteMarker();
        // }
        // if(this.active == 2){
        //     this.plotFleetMarker();
        // }
        // if(this.active == 3){
        //     this.plotDriverMarker();
        // }
    }

    showPickUp(event){
        this.pickupCheck = event.target.checked;
        // if(this.active == 1){
        //     this.plotRouteMarker();
        // }
        // if(this.active == 2){
        //     this.plotFleetMarker();
        // }
        // if(this.active == 3){
        //     this.plotDriverMarker();
        // }
    }

    applyFilter(){
        
        this.getParentComponent().markers = [];
        this.getParentComponent().latestLog = [];
        this.getParentComponent().delmarkers = [];
        if(this.active == 1){
            this.plotRouteMarker();
        }
        if(this.active == 2){
            this.plotFleetMarker();
            this.plotRouteMarker();
        }
        if(this.active == 3){
            this.plotDriverMarker();
            this.plotRouteMarker();
        }
    }
    
    addRouteId(event){
        console.log(event);
        this.route.push(event.routeId);
    }

    getRandomColor() {
        var color = Math.floor(0x1000000 * Math.random()).toString(16);
        return '#' + ('000000' + color).slice(-6);
    }
}