import { Component, Injector, OnInit, ViewChild, ViewEncapsulation, ElementRef, AfterViewInit, Renderer, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AppConsts } from '@shared/AppConsts';
import { CommonModule } from '@angular/common';  
import { appModuleAnimation } from '@shared/animations/routerTransition';

import { AppComponentBase } from '@shared/common/app-component-base';
import { RouteListDto, 
         RouteServiceProxy,
         LocationListDto,
         LocationServiceProxy,
         ControllerRouteServiceProxy,
         GenerateRouteInputDto,
         AddressAddressTypeLookupTableDto,
        //  ControllerRouteDetailServiceProxy

} from '@shared/service-proxies/service-proxies';

import * as moment from 'moment';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { HttpClient } from '@angular/common/http';
import { finalize } from 'rxjs/operators';
import * as _ from 'lodash';
import { TabsetComponent } from 'ngx-bootstrap';

import { TableRoutesComponents } from './table-routes-details.component';
import { ControllerRoutesService } from './croutes.service';
import { ControllerShowHideComponent } from '@app/sprintship/controller/core-components/controller-show-hide-modal.component.ts';
import { CreateRouteControllerModalComponent } from '@app/sprintship/controller/modals/create-routes-controller-modal.component';
import { DriverListTabComponent } from '../../controller/drivers/driver-list.component';
import { KPIBoxComponent } from '../kpi-box/kpi-box.component';
import { VehicleListTabComponent } from '../vehicles/vehicle-list.component';
import { AppSessionService } from '@shared/common/session/app-session.service';

import { GenerateRoutesTrackingComponent } from './generate-routes-tracking.component';
import { interval } from 'rxjs';
import * as signalR from '@aspnet/signalr';
import { OrderListTabComponent } from '../orders/order-list.component';

import * as controller_table_settings from '@app/sprintship/controller/core-components/controller-table-settings.json';

declare var $: any;
declare var jquery:any;
@Component({
    selector: 'controller-main',
    templateUrl: 'croutes.component.html',
    encapsulation: ViewEncapsulation.None,
    styleUrls: ['./croutes.component.less', './dropdown.component.less'],
    animations: [appModuleAnimation()],
    providers: [ControllerRoutesService]
})

export class CRoutesComponent extends AppComponentBase implements OnInit {

    private hubConnection: signalR.HubConnection

    @ViewChild('controllerTab', { static: false }) staticTabs: TabsetComponent;
    @ViewChild('controllerTab', { read: ElementRef, static: true }) cRef: ElementRef;
    @ViewChild(TableRoutesComponents, {static: false}) tRouteComponents: TableRoutesComponents;
    @ViewChild(DriverListTabComponent, {static: false}) tDriverComponents: DriverListTabComponent;
    @ViewChild(VehicleListTabComponent, {static: false}) tVehicleComponents: VehicleListTabComponent;
    @ViewChild(OrderListTabComponent, {static: false}) tOrderComponents: OrderListTabComponent;
    @ViewChild(KPIBoxComponent, {static: false}) tKpiComponents: KPIBoxComponent;
    // @ViewChild(KPIBoxComponent, {static: false}) tKpiBoxComponents: KPIBoxComponent;
    @ViewChild('dr', { static: false }) dr : ElementRef;
    @ViewChild('columnChooser', {static: false}) columnChooser: ControllerShowHideComponent;

    @ViewChild('generateRoutesTracking', {static: false}) generateRoutesTracking: GenerateRoutesTrackingComponent;
    @ViewChild('createRouteControllerModal', {static: false}) createRouteControllerModal: CreateRouteControllerModalComponent;

    locations: LocationListDto[] = [];
    hide: boolean = true;
    hide_menu: boolean = true;
    key: number;
    tblMain: any;
    todaysDate: Date;
    event: LazyLoadEvent;
    generateEnable: boolean;

    filters: {
        locationFilter: number;
        statusFilter: number;
        typeFilter: number;
        startDate: Date;
        endDate: Date;
    } = <any>{};
    search_string: string;
    txtFilter: string;
    driverListComponent: boolean = false;
    vehicleListComponent: boolean = false;
    statusLocatorComponent: boolean = false;
    
    orderPackageListComponent: boolean = false;
    orderListComponent: boolean = false;
    heightTemp: string;

    inputs: {
        locationId: number;
        loadDate: Date;
    } = <any>{};

    @Input('edition_name') edition: string;
	constructor(
        injector: Injector,
        private _controllerRouteService: ControllerRouteServiceProxy,
        private _locationServiceProxy: LocationServiceProxy,
        private _routeService: RouteServiceProxy,
        private _cRoutesService: ControllerRoutesService,
        private renderer: Renderer, 
        private elem: ElementRef
    ) {
        super(injector);

        this.todaysDate = new Date(Date.now());
        this.filters.startDate = this.todaysDate;
        this.filters.endDate = this.todaysDate;
        this.generateEnable = false;
        
    }

    hideKpi(): void {
     
        if (this.hide == true)
        {   
            this.hide = false;
            $('#kpiToggleIcon').removeClass('fa-eye-slash');
            $('#kpiToggleIcon').addClass('fa-eye');
        } 
        else 
        {
            this.hide = true;
            $('#kpiToggleIcon').addClass('fa-eye-slash');
            $('#kpiToggleIcon').removeClass('fa-eye');
        }
    }

    hideMenu(): void {         

        if (this.hide_menu == true)
        {
            $('.dropdown-controller-menu').css('display', 'block');
            this.hide_menu = false;
        } 
        else 
        {
            $('.dropdown-controller-menu').css('display', 'none');
            this.hide_menu = true;
        }
    }

    showColumnChooser()
    {
        this.columnChooser.show();
    }

    ngOnInit(): void {

        let that = this;
       
        this.todaysDate = new Date(Date.now());
        this.spinnerService.show();
        $("#kt_datetimepicker_6").val(moment(that.todaysDate).format('MM/DD/YYYY')); 
        this.getLocationsOnLoad().then(function(result){
            that.filters.startDate = that.todaysDate;
            that.filters.endDate = that.todaysDate;
            $('#kt_daterangepicker_2 .form-control').val( moment(that.todaysDate).format('YYYY-MM-DD') + ' / ' + moment(that.todaysDate).format('YYYY-MM-DD'));
            $('#hiddenStartDate').val(that.filters.startDate);
            $('#hiddenEndDate').val(that.filters.endDate);
            that.tKpiComponents.getKpiCount();
            console.log(that.tRouteComponents);
            that.tRouteComponents.populateTable();
            that.spinnerService.hide();
            that.inputs.loadDate = that.filters.startDate;
            that.inputs.locationId =that.filters.locationFilter;
        });
        
        $('.selLocation').select2();
        $('#kt_daterangepicker_2').daterangepicker({
            buttonClasses: ' btn',
            applyClass: 'btn-primary',
            cancelClass: 'btn-secondary'
        }, function(start, end, label) {
            $('#kt_daterangepicker_2 .form-control').val( start.format('YYYY-MM-DD') + ' / ' + end.format('YYYY-MM-DD'));
            $('#hiddenStartDate').val(start.format('YYYY-MM-DD'));
            $('#hiddenEndDate').val(end.format('YYYY-MM-DD'));

            that.filters.startDate = $('#hiddenStartDate').val();
            that.filters.endDate = $('#hiddenEndDate').val();  
            
        });
        $('#locationSelectInput').on('change', function(){
            $("#locationSelectInput").val($(this).val());
            that.filters.locationFilter = $("#locationSelectInput").val();
        });

        var heightTmp = (parseInt($('.kt-grid__item').height()) - (parseInt($('.kt-subheader').height()) * 3)) - 370;
        this.heightTemp =heightTmp.toString() + 'px';
        this.cRef.nativeElement.querySelectorAll('#tblRoutes .primeng-datatable-container')[0].style.height = this.heightTemp;

        this.backgroundProcessListener();
        console.log(this.edition);
        console.log(controller_table_settings);
    }


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


    loadRouteComponent(){
        this.statusLocatorComponent = false;
    }

    filterRoutes()
    {

        let that = this;
        let ktHolder = $('#kt_datetimepicker_6').val().split('/');
        let nowDate = moment(this.todaysDate).toDate();
        let nowDateMoment = moment(nowDate);
        let endDate = new Date(ktHolder[2], ktHolder[0] - 1, ktHolder[1]);
        let duration = {};
        duration['_data'] = {'days': 0};
        endDate = moment(endDate).toDate();
        duration = moment.duration(nowDateMoment.diff(endDate));
        console.log('DURATION: ');
        if(typeof duration !== "undefined")
        {    
            
            if(duration['_data'].days > 0)
            {
                this.generateEnable = true;
            }        
            else
            {
                this.generateEnable = false;
            }    
        }
        this.filters.startDate = $('#kt_datetimepicker_6').val();
        this.filters.endDate = $('#kt_datetimepicker_6').val();
        this.inputs.loadDate = that.filters.startDate;
        
        this._cRoutesService.setStatistics({"result": "OK", "total_vehicles": "0", "total_packages": "0"});
        that.filters.locationFilter = $("#locationSelectInput").val();
        this.inputs.locationId =that.filters.locationFilter;
        that.tRouteComponents.populateTable();
        // that.tDriverComponents.getDriverList(this.event);
        that.tKpiComponents.getKpiCount();

    }
    loadDriverListComponent(){
        this.driverListComponent = true;
    }
    loadVehicleListComponent(){
        this.vehicleListComponent = true;
    }

    loadOrderPackagesListComponent(){
        this.orderPackageListComponent = true;
    }


    loadOrderListComponent(){
        
        let that = this;
        this.orderListComponent = true;
        that.filters.locationFilter = $("#locationSelectInput").val();
        this.filters.startDate = $('#kt_datetimepicker_6').val();
        this.filters.endDate = $('#kt_datetimepicker_6').val();
        this.getLocationsOnLoad();
        this.tOrderComponents.getOrder(undefined);
    }

    getSelected()
    {
        //console.log('T COMPONENTS: ');
        let elements = this.elem.nativeElement.querySelectorAll('.checkboxItem');
        //console.log(elements);
    }
    filterRoutesByParameters()
    {
        //console.log($('#txtFilter').val());
        this.search_string = this.txtFilter;
        this.tRouteComponents.setFilter(this.txtFilter);
        this._cRoutesService.setStatistics({"result": "OK", "total_vehicles": "0", "total_packages": "0"});
        this.tRouteComponents.populateTable();
    }


    backgroundProcessListener() {

        this.hubConnection = new signalR.HubConnectionBuilder()
            .withUrl(AppConsts.remoteServiceBaseUrl + '/signalr-background')
            .build();

        this.hubConnection
            .start()
            .then(() => console.log('Connection started'))
            .catch(err => console.log('Error while starting connection: ' + err));


        this.hubConnection.on('BackgroundMessage', (message) => {
            
            this.generateRoutesTracking.logMessage(message);
        });
    }
    showCreateRoutes() {
        this.createRouteControllerModal.show();
    }
    refresh(event: any) {
        this.filterRoutes();
    }
    async generateRoute()
    {
        this.generateRoutesTracking.clearMessages();
        
        this.filters.startDate = $('#hiddenStartDate').val();
        this.filters.endDate = $('#hiddenEndDate').val();
        this.filters.locationFilter = $("#locationSelectInput").val();

        let params = new GenerateRouteInputDto({
            loadDateEnd: moment(this.filters.endDate),
            loadDateStart: moment(this.filters.startDate),
            locationId: this.filters.locationFilter,
            action: "RUN",
            jobId: ""
        });

        let runResult = await this._controllerRouteService.generateRouteManual(params).toPromise();

        if(runResult.success) {

            if(runResult.jobId) {

                this.generateRoutesTracking.modal.show();

                params.jobId = runResult.jobId;

                params.action = "TRACK";

                let observable = interval(2000).subscribe((val) => { 

                    this._controllerRouteService.generateRouteManual(params).subscribe(watcher => {

                        if(watcher.result == "DONE") {

                            this.generateRoutesTracking.complete();

                            observable.unsubscribe();

                            this.filterRoutes();
                        }
                    });
                });
            }
        }
    }

}