import {
    Component,
    Injector,
    OnInit,
    ViewChild,
    ViewEncapsulation,
    Input,
    OnDestroy,
    ElementRef,
    Renderer,
    QueryList,
    ViewChildren
} from '@angular/core';
import {
    ActivatedRoute,
    Router
} from '@angular/router';
import {
    AppConsts
} from '@shared/AppConsts';
import {
    appModuleAnimation
} from '@shared/animations/routerTransition';
import {
    AppComponentBase
} from '@shared/common/app-component-base';
import {
    RouteListDto,
    RouteServiceProxy,
    ControllerRouteServiceProxy,
    ControllerKpiCountServiceProxy
    
} 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 {
    Subscription
} from 'rxjs';
import {
    CheckBoxComponent
} from '@app/sprintship/core-components/checkbox/checkbox.component.ts';
import {
    StatusComponent
} from '@app/sprintship/controller/status/status.component.ts';

import { ControllerRoutesService } from '@app/sprintship/controller/routes/croutes.service';
import * as _ from 'lodash';

import { KPIBoxComponent } from '@app/sprintship/controller/kpi-box/kpi-box.component';


declare var $: any;
declare var jquery: any;
@Component({
    selector: 'table-routes-laboratory-details',
    templateUrl: 'table-routes-laboratory-details.component.html',
    encapsulation: ViewEncapsulation.None,
    styleUrls: ['./table-routes-laboratory-details.component.less', './tables.checkbox.component.less'],
    animations: [appModuleAnimation()]
})

export class TableRoutesLaboratoryComponents extends AppComponentBase implements OnInit, OnDestroy {

    @ViewChild('dataTable', {
        static: true
    }) dataTable: Table;
    @ViewChild('paginator', {
        static: true
    }) paginator: Paginator;
    @ViewChildren('CheckBoxComponent') chkBoxList: QueryList < any > ;
    @ViewChildren(KPIBoxComponent) tKpiBoxComponents: KPIBoxComponent;
    @ViewChild(StatusComponent, {static: false}) statusDiv: StatusComponent;
    @Input() filters: {
        locationFilter: number;
        statusFilter: number;
        typeFilter: number;
        startDate: Date;
        endDate: Date
    } = < any > {};
    device_type: string;
    routeIds: any;
    attr: any;
    respkey: any;
    @Input('search_string') search: string;

    subscription: Subscription;
    private cBox: CheckBoxComponent;
    constructor(
        injector: Injector,
        private _routeService: RouteServiceProxy,
        private _controllerRouteService: ControllerRouteServiceProxy,
        private _cRoutesService: ControllerRoutesService,
        private _cKpiService : ControllerKpiCountServiceProxy,
        private router: Router,
        private renderer: Renderer,
        private elem: ElementRef

    ) {
        super(injector);
        this.subscription = _cRoutesService.setStatisticsObj.subscribe(details => {
            // console.log('RECEIVED');
            // console.log(details);
        });
    }

    ngOnInit(): void {

    }
    setFilter(value: string) {
        this.search = value;
    }
    ngOnDestroy(): void {

    }
    populateTable(event ? : LazyLoadEvent): void {
        var that = this;
        var key, arrResult = [], resp;
        this.attr = [];
        that.routeIds = [];
        console.log('PAGINATOR: ');
        console.log(this.paginator);
        if (this.filters.locationFilter !== undefined) {
            this.device_type = 'IOS';
            // that.primengTableHelper.defaultRecordsCountPerPage = 50;
            if (this.primengTableHelper.shouldResetPaging(event)) {
                this.paginator.changePage(0);
                return;
            }

            this.filters.startDate = new Date(this.filters.startDate.toString());
            this.filters.endDate = new Date(this.filters.endDate.toString());
            let startDate = moment(moment(this.filters.startDate).format('YYYY-MM-DD HH:mm:ss'));
            let endDate = moment(moment(this.filters.endDate).format('YYYY-MM-DD HH:mm:ss'));

            let startDateA = startDate['_i'].split(' ');
            startDateA = startDateA[0] + ' ' + '00:00:00';

            let endDateA = endDate['_i'].split(' ');
            endDateA = endDateA[0] + ' ' + '23:59:59';
            that.spinnerService.show();
            this._controllerRouteService.getFullListAntechEdition(undefined, this.filters.locationFilter, undefined, undefined, this.search, moment.utc(moment(startDateA).toISOString()), moment.utc(moment(endDateA).toISOString()), this.primengTableHelper.getSorting(this.dataTable), this.primengTableHelper.getMaxResultCount(this.paginator, event), this.primengTableHelper.getSkipCount(this.paginator, event))
                .subscribe(result => {
                    let finalResult = {};
                    let fResult = {
                        "result": "OK",
                        "total_vehicles": 0,
                        "total_packages": 0
                    };
                    let vehicles = [];
                    for (key in result.items) {
                        that.routeIds.push(result.items[key].routeId);
                        result.items[key]['Status'] = 'NONE';
                        result.items[key]['TotalPackages'] = 0;
                        result.items[key]['ETA'] = 'N/A';
                        vehicles[result.items[key].vehicleId] = result.items[key].vehicleId;
                    }
                    fResult.total_vehicles = Object.keys(vehicles).length;
                    
                    that._controllerRouteService.getDetailsAntechEdition(that.routeIds)
                        .subscribe(resultStatus => {
                           
                            
                            let total_packages = 0;
                            if (resultStatus == null) {

                            } else {
                                   
                                if (Object.keys(resultStatus).length > 0) {
                                    var resp;
                                    for (key in resultStatus) {
                                        resp = that.filterArrayKeys(result.items, 'routeId', resultStatus[key].routeId.toString());

                                        if(resp !== null)
                                        {
                                            result.items[resp]['Status'] =  resultStatus[key].statusCode;
                                            result.items[resp]['TotalPackages'] =  resultStatus[key].totalPackages;
                                            result.items[resp]['TotalPickedUp'] =  resultStatus[key].totalPickedUp;
                                        }

                                        //$('#route' + resultStatus[key].routeId).html(resultStatus[key].totalPackages);
                                        //$('#status' + resultStatus[key].routeId).attr('status_code', resultStatus[key].statusCode);
                                        //$('#statusRow' + resultStatus[key].routeId).html('<status status_code="'+resultStatus[key].statusCode+'" #statusCode></status>');
                                        // $('#statusRow' + resultStatus[key].routeId).html('<ng-container *ngTemplateOutlet="waitingPickup; context: myContext"></ng-container>');
                                        that.attr[resultStatus[key].routeId] = resultStatus[key].statusCode;
                                        total_packages = total_packages + resultStatus[key].totalPackages;
                                    }
                                }
                            
                                console.log('RESULT ITEMS: ');
                                console.log(result.items);
                            }
                            
                            that.primengTableHelper.totalRecordsCount = result.totalCount;
                            that.primengTableHelper.records = result.items;
                            fResult.total_packages = total_packages;
                            that._cRoutesService.getTableStatistics(fResult);

                        });

                    that.spinnerService.hide();

                });
        }
    }
    tickBox() {
        this.cBox.tickBox();
    }
    getSelected() {
        console.log(this.chkBoxList);
        this.chkBoxList.forEach(chkBoxL => console.log(chkBoxL));
    }
    filterArray(array:any, key:any, value:any)
    {
        var i, arrList = [];
        for(i in array)
        {
            console.log('SEARCH');
            console.log(array[i][key]);
            console.log(value);
            if(array[i][key] == value)
            {
                arrList.push(array[i]);
            }
        }
        return arrList;
    }
    filterArrayKeys(array:any, key:any, value:any)
    {        
        var i, keys = 0;
        for(i in array)
        {
            if(array[i][key] == value)
            {
                keys = i;
            }
        }
        return keys;
    }
    openMap(userId, routeId) {
        // window.open('/app/sprintship/locator/'+routeId+'/'+this.filters);
        this.router.navigate([]).then(result => {
            window.open('/app/sprintship/locator/' + userId + '/' + this.filters.locationFilter + '/' + routeId + '/' + moment(this.filters.startDate).format('YYYY-MM-DD') + '/' + moment(this.filters.endDate).format('YYYY-MM-DD'), '_blank');
        });
    }
}