import { Component, Injector, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { VehicleServiceProxy, VehicleListDto, CreateVehicleInput} from '@shared/service-proxies/service-proxies';
import * as jquery from 'jquery';
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';

@Component({
    templateUrl: './vehicles.component.html',
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()]
})
export class VehiclesComponent extends AppComponentBase{

    @ViewChild('dataTable', {static: true}) dataTable: Table;
    @ViewChild('paginator', {static: true}) paginator: Paginator;

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

    newVehicle: CreateVehicleInput = null;

    constructor(
        injector: Injector,
        private _vehicleService:VehicleServiceProxy
    ) {
        super(injector);
    }
    
    getVehicle(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);

            return;
        }

        this.spinnerService.show();

        this._vehicleService.getVehiclePaged(
            this.filters.id,
            this.filters.vehicleName,
            undefined,
            undefined, 
            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());
    }

    deleteVehicle(vehicle: VehicleListDto): void {
        this.message.confirm(
            this.l('VehicleDeleteWarningMessage', vehicle.name),
            this.l('AreYouSure'),
            (isConfirmed) => {
                if (isConfirmed) {
                    this._vehicleService.deleteVehicle(vehicle.id)
                        .subscribe(() => {
                            this.reloadPage();
                            this.notify.success(this.l('SuccessfullyDeleted'));
                        });
                }
            }
        );
    }
   
}

