import { Component, Injector, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { FleetServiceProxy, FleetListDto, CreateFleetInput} from '@shared/service-proxies/service-proxies';

import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/table';
import { HttpClient } from '@angular/common/http';
import { finalize } from 'rxjs/operators';
//import { CreateVehicleModalComponent } from './create-vehicle-modal.component';

@Component({
    templateUrl: './fleets.component.html',
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()]
})
export class FleetsComponent extends AppComponentBase{
    @ViewChild('dataTable', {static: true}) dataTable: Table;
    @ViewChild('paginator', {static: true}) paginator: Paginator;
   // @ViewChild('createVehicleModal') createVehicleModal: CreateVehicleModalComponent;


   filters: {
        id: number;
        name: string;
    } = <any>{};

    newFleet: CreateFleetInput = null;

    constructor(
        injector: Injector,
        private _fleetService:FleetServiceProxy
    ) {
        super(injector);
    }
    
    getFleet(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);
            return;
        }

        this.spinnerService.show();

        this._fleetService.getFleetPaged(
            this.filters.id,
            this.filters.name,
            this.primengTableHelper.getSorting(this.dataTable),   
            this.primengTableHelper.getMaxResultCount(this.paginator, event),        
            this.primengTableHelper.getSkipCount(this.paginator, event),
        ).pipe(finalize(() => this.spinnerService.hide())).subscribe(result => {
            this.primengTableHelper.totalRecordsCount = result.totalCount;
            this.primengTableHelper.records = result.items;
            this.spinnerService.hide();
            
        });

    }

    reloadPage(): void {
        this.paginator.changePage(this.paginator.getPage());
    }

    deleteFleet(fleet: FleetListDto): void {

        this.message.confirm(
            this.l('FleetDeleteWarningMessage', fleet.name),
            this.l('AreYouSure'),
            (isConfirmed) => {
                if (isConfirmed) {
                    this._fleetService.deleteFleet(fleet.id)
                        .subscribe(() => {
                            this.reloadPage();
                            this.notify.success(this.l('SuccessfullyDeleted'));
                        });
                }
            }
        );
    }
   
}

