import { Component, ViewEncapsulation, Injector, OnInit, DoCheck, ViewChild, Input } from "@angular/core";
import { appModuleAnimation } from "@shared/animations/routerTransition";
import { AppComponentBase } from "@shared/common/app-component-base";
import { Router, ActivatedRoute } from "@angular/router";
import * as moment from 'moment';
import { LocationServiceProxy, LocationListDto } from "@shared/service-proxies/service-proxies";
import { MapFlyOutComponent } from "@app/shared/layout/flyout/map/map-flyout.component";
import { empty } from "rxjs";
import { LaboratoryMapFlyOutComponent } from "@app/shared/layout/flyout/map/laboratory/laboratory-map-flyout.component";
declare var $: any;

@Component({
    templateUrl: './locator.component.html',
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()],
    styleUrls: ['./locator.component.less']
})

export class LocatorComponent extends AppComponentBase implements OnInit{
    
    @Input() markers: marker[] = []; 
    @Input() latestLog: marker[] = []; 
    @Input() delmarkers: marker[] = []; 
    @Input() driverP: marker[] = []; 
    route: Array<any> = [];
    routeIds: Array<any> = [];  
    routeSel: Array<any> = [];
    active: number;
    activeF: number;
    activeD: number;
    locations: LocationListDto[] = [];
    filters: {
        locationFilter: number;
        statusFilter: number;
        typeFilter: number;
        startDate: Date;
        endDate: Date;
    } = <any>{};
    
    todaysDate = moment().format('MM/DD/YYYY');

    zoom: number = 14;
    // initial center position for the map
    lat: number = 34.044971;
    lng: number = -118.291243;
    map: any;
    pin: { path: string; fillColor: string; fillOpacity: number; strokeColor: string; strokeWeight: number; scale: number; labelOrigin: { x: number; y: number; }; };
    
    laboratoryMapFeatureEdition: boolean = false;
    
    @ViewChild('laboratoryMapFlyOutComponent', {static: false}) laboratoryMapFlyOutComponent: LaboratoryMapFlyOutComponent;
    @ViewChild('mapFlyOutComponent', {static: false}) mapFlyOutComponent: MapFlyOutComponent;

    constructor(
        injector: Injector,
        private router: Router,
        private _locationServiceProxy: LocationServiceProxy,
        private activatedRoute: ActivatedRoute,
    ) {
        super(injector);
        
        this.laboratoryMapFeatureEdition = abp.features.isEnabled('App.LaboratoryMapFilter');
        // this.todaysDate = moment();
    }


    ngOnInit(): void {
        this.activatedRoute.paramMap.subscribe(params => {
            this.filters.locationFilter = +params.get("location");
            this.filters.startDate = new Date(params.get("dateStart"));
            this.filters.endDate = new Date(params.get("dateEnd"));
            this.route = [+params.get("id")];
            this.active = 1;
            this.activeD = 1;
            this.activeF = 1;
            this.routeIds = [+params.get('rid')];
            this.routeSel = [+params.get('rid')];
        });
        
        let that = this;
        this.spinnerService.show();
        if(that.route[0] != 0){
            $('#map_datepicker .form-control').val( moment(that.filters.startDate).format('YYYY-MM-DD') + ' / ' + moment(that.filters.endDate).format('YYYY-MM-DD') );
            $('#hiddenStartDateMap').val(that.filters.startDate);
            $('#hiddenEndDateMap').val(that.filters.endDate);
        }else{
            $('#map_datepicker .form-control').val( moment(that.todaysDate).format('YYYY-MM-DD') + ' / ' + moment(that.todaysDate).format('YYYY-MM-DD'));
            $('#hiddenStartDateMap').val(moment(that.todaysDate).format('YYYY-MM-DD'));
            $('#hiddenEndDateMap').val(moment(that.todaysDate).format('YYYY-MM-DD'));
            that.filters.startDate = $('#hiddenStartDateMap').val();
            that.filters.endDate = $('#hiddenEndDateMap').val(); 
        }
        this.getLocationsOnLoad().then(function(result){
            that.spinnerService.hide();
        });
        $('#map_datepicker').daterangepicker({
            buttonClasses: ' btn',
            applyClass: 'btn-primary',
            cancelClass: 'btn-secondary'
        }, function(start, end) {
            $('#map_datepicker .form-control').val( start.format('YYYY-MM-DD') + ' / ' + end.format('YYYY-MM-DD'));

            $('#hiddenStartDateMap').val(start.format('YYYY-MM-DD'));
            $('#hiddenEndDateMap').val(end.format('YYYY-MM-DD'));

            that.filters.startDate = $('#hiddenStartDateMap').val();
            that.filters.endDate = $('#hiddenEndDateMap').val();  
        });
        
        // $("#locationSelectInputMap").val(that.filters.locationFilter);
        $('#locationSelectInputMap').on('change', function(){
            $("#locationSelectInputMap").val($(this).val());
            that.filters.locationFilter = $("#locationSelectInputMap").val();
        });
        
    }

    getLocationsOnLoad()
    {
        let that = this;
        return new Promise(function(resolve, reject){
            that._locationServiceProxy.getLocation(undefined, undefined, undefined, undefined, undefined, undefined, undefined)
                .subscribe(result => {
                    $('#locationSelectInputMap').select2();
                    that.locations = result.items;
                    if(that.filters.locationFilter != 0){
                        $("#locationSelectInputMap").val(that.filters.locationFilter);
                    }else{
                        that.filters.locationFilter = result.items[0].id;
                        $("#locationSelectInputMap").val(result.items[0].id);
                        resolve(result.items[0].id);
                    }
                });
        });
    }

    // ngDoCheck() {
    //     // ...
    //     console.log(this.filters);
    // }
    onChange(event){
        console.log(event);
    }
    
    showFlyOut(clickby): void {
        if(clickby == 1){
            $("#getting_started_toggle").click();
            if(this.laboratoryMapFeatureEdition){
                this.laboratoryMapFlyOutComponent.unselectAll();
                this.laboratoryMapFlyOutComponent.loadFlyOut();
            }else{
                this.mapFlyOutComponent.unselectAll();
                this.mapFlyOutComponent.loadFlyOut();
            }
        }else{

            if(this.laboratoryMapFeatureEdition){
                this.laboratoryMapFlyOutComponent.loadFlyOut();
            }else{
                this.mapFlyOutComponent.loadFlyOut();
            }
        }
    }


    mapReady(event: any) {
        this.map = event;
            
        this.markers = [];
        this.latestLog = [];
        this.delmarkers = [];
        this.driverP = [];
    }

    clickedMarker(label: string, index: number) {
    // console.log(`clicked the marker: ${label || index}`)
    }

    recenterMap(lt, lg){
        this.lat = lt;
        this.lng = lg;
        this.zoom = 22;
      }
 
}

// just an interface for type safety.
interface marker {
	lat: number;
	lng: number;
	label?: string;
    draggable: boolean;
    icon?: { path: string; fillColor: string; fillOpacity: number; strokeColor: string; strokeWeight: number; scale: number; labelOrigin: { x: number; y: number; } };
    driverName: string;
    orderId:string;
    eta:string;
    color?:string;
    companyName?:string;
    geocode?:number;
}
