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, RouteTypeList, GetVehicleDestinationPointsResultDto } from "@shared/service-proxies/service-proxies";
import { MapsAPILoader } from "@agm/core";
import { stringify } from "querystring";
import { Options } from "select2";
import { List } from "lodash";

@Component({

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

})

export class LaboratoryMapFlyOutComponent extends AppComponentBase implements AfterViewInit, OnInit{

    @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> = [];
    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;
    @Input() activeF: number;
    @Input() activeD: number;
    select: Array<any> = [];
    driver: Array<any> = [];
    locations: any;
    listpick: Array<any> = [];
    routeType: List<RouteTypeList>;
    @Input() routeSel: Array<any> = [];

    @Input() routeIds: Array<any> = [];
    routeTypeIds: Array<any> = [];
    recenter: number;
    constructor(
        private viewContainerRef: ViewContainerRef,
        injector:Injector,
        private el: ElementRef,
        private router:Router,
        private _locatorAppService: LocatorServiceProxy
    ){
        super(injector)  
    }

    _isOpen: boolean;
    _pinned = false;
    
    ngOnInit(){
        this._locatorAppService.getRouteType().subscribe((result)=>{
            this.routeType = result.items;
            result.items.forEach(item => {
                this.routeTypeIds.push(item.id);
            });
        });
        
        if(this.route[0] != 0){
            this._locatorAppService.getRouteFilter(moment(this.filters.startDate),moment(this.filters.endDate),this.filters.locationFilter,undefined,undefined,undefined)
            .subscribe((result)=>{
                this.driver = [];
                this.data = result.items;
                this.plotRouteMarker();
            });
        }else{
            this.route = [];
            this.routeSel = [];
            this.routeIds = [];
        }

    }

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

        this.routeClick();

    }

    routeClick(){
        this.active = 1;
        this._locatorAppService.getLaboratoryDriverFilter(moment(this.filters.startDate),moment(this.filters.endDate),this.filters.locationFilter,undefined,undefined,this.routeIds)
        .subscribe((result)=>{
            this.data = result.items;
        });
    }

    selectAll() {
            this.route = this.data.map(x => x.userId);
            this.routeIds = this.data.map(x => x.routeId);
            this.routeSel = this.data.map(x => x.routeId);
    }

    unselectAll() {
        this.route = [];
        this.routeSel = [];
        this.routeIds = [];
        this.driver = [];
        this.getParentComponent().markers = [];
        this.getParentComponent().latestLog = [];
        this.getParentComponent().delmarkers = [];
        this.getParentComponent().driverP = [];
        this.activeF = 0;
        this.activeD = 0;
    }
    
    clearAll() {
        this.route = [];
        this.routeSel = [];
        this.routeIds = [];
        this.driver = [];
        this.getParentComponent().markers = [];
        this.getParentComponent().latestLog = [];
        this.getParentComponent().delmarkers = [];
        this.getParentComponent().driverP = [];
        this.activeF = 0;
        this.activeD = 0;
    }

    addRoute(event){
        this.routeIds.push(event.routeId);
        this.route.push(event.userId);
        this.routeSel.push(event.routeId);
    }

    plotRouteMarker(){
        var color = '';
        this.getParentComponent().markers = [];
        this.getParentComponent().latestLog = [];
        this.getParentComponent().delmarkers = [];
        this.getParentComponent().driverP = [];
        if(this.route.length != 0){
            
            this.spinnerService.show();
            this._locatorAppService.getLaboratoryDriverDestinationPoints(moment(this.filters.startDate),moment(this.filters.endDate),this.filters.locationFilter,this.route,this.routeTypeIds,this.routeIds)
            .subscribe((result)=>{
                this.points = result.items;
                let geocodearray1 = Array<any>();
                let geocodearray = Array<any>();
                this.points.forEach(item => {
                    if(this.pickupCheck){
                        this.getParentComponent().markers.push(
                            {
                                lat: item.pickUpLatitude,
                                lng: item.pickUpLongtitude,
                                label: item.orderNumber+"",
                                draggable: false,
                                // pin: pin,
                                driverName: item.driverName,
                                orderId: item.orderId,
                                eta: moment(item.eta).toString(),
                                color: item.color,
                                companyName: item.pickUpCompanyName,
                                geocode: item.pickUpGeoCodeId

                            });
                        
                        if(geocodearray1.indexOf(item.pickUpGeoCodeId) !== -1) {

                        }else{
                            this.listpick.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: item.color,
                                companyName: item.pickUpCompanyName,
                                geocode: item.pickUpGeoCodeId
                            })
                        }
                        geocodearray1.push(item.pickUpGeoCodeId);
                    }

                    if(this.deliveryCheck){
                        if(geocodearray.indexOf(item.deliveryGeoCodeId) !== -1) {
                            // console.log('connn');
                        }else{
                            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: item.color,
                                    companyName: item.deliveryCompanyName,
                                    geocode: item.deliveryGeoCodeId
                                });
                        }
                        geocodearray.push(item.deliveryGeoCodeId);
                    }
                });
                this.locations = this.listpick.concat(this.getParentComponent().delmarkers);
                this.spinnerService.hide(); 
            })
        }

        if(this.activeF == 1){
            if(this.route.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,this.routeIds)
                .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();
                })
            }
        }

        if(this.activeD == 1){
            if(this.route.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.route,undefined,this.routeIds)
                .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();
                })
            }
        }
    }

    clickRouteType(event, routeTypeid){
        
        // this.route = this.data.map(x => x.userId);
        if(event.target.checked){
            this.routeTypeIds.push(routeTypeid);
        }else{
            var index = this.routeTypeIds.indexOf(routeTypeid);
            if (index > -1) {
                this.routeTypeIds.splice(index, 1);
            }
        }
        this.plotRouteMarker();
    }

    plotFleetMarker(){
        var color = '';
        if(this.activeF == 1){
            this.activeF = 0;
            this.getParentComponent().latestLog = [];
        }else{
            this.activeF = 1;
            if(this.route.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,this.routeIds)
                .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.activeD == 1){
            this.activeD = 0;
            this.getParentComponent().driverP = [];
        }else{
            this.activeD = 1;
            if(this.route.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.route,undefined,this.routeIds)
                .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();
                })
            }
        }
    }

    reCenteMap(){
        var result = this.locations.find(obj => {
            return obj.geocode === this.recenter
          });
          this.getParentComponent().recenterMap(result.lat, result.lng);
    }

}