import { Component, ViewChild, Injector, ElementRef, Output, EventEmitter } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { VehicleServiceProxy, UpdateVehicleInput, UserServiceProxy,UserListDto, DriversServiceProxy } from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
declare var $: any;

@Component({
  selector: 'editVehicleModal',
  templateUrl: './edit-vehicle-modal.component.html'
})
export class EditVehicleModalComponent extends AppComponentBase {

  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

  @ViewChild('modal', {static: false})modal: ModalDirective;
 @ViewChild('nameInput', {static: false}) nameInput: ElementRef;

  vehicle: UpdateVehicleInput = new UpdateVehicleInput();
  users: UserListDto[] = [];
  defaultUser: any;
  userInput: {
    id: number,
    name: string
  };

  txtUser: any;

  active: boolean = false;
  saving: boolean = false;

  constructor(
    injector: Injector,
    private _vehicleService: VehicleServiceProxy,
    private _driverService: DriversServiceProxy

  ) {
    super(injector);
  }

  show(vehicleId: any): void {
    let maxcount = 1000;
    this.active = true;
    this._vehicleService.getVehicleForEdit(
        vehicleId     
        ).subscribe((result)=> {
      this.vehicle = result.vehicle;
      result.vehicle.user === undefined ? this.defaultUser = undefined: this.defaultUser = result.vehicle.user.id;
      this.showAllDriver(maxcount);
      this.modal.show();
    });

  }

  onShown(): void {
    $('.kt-select2').select2();
  }


  showAllDriver(maxcount): void {
    this.active = true;

    this._driverService.getDrivers(undefined,undefined,undefined, undefined, undefined, maxcount, undefined).subscribe((result) => {
        this.users = result.items;

    });

  }

  save(): void {
   
    this.vehicle.userId =  Number((<HTMLInputElement>document.getElementById('txtUser')).value);
    this.saving = true;
    this._vehicleService.updateVehicle(this.vehicle)
      .subscribe(() => {
        this.notify.info(this.l('SavedSuccessfully'));
        this.close();
        this.modalSave.emit(this.vehicle);
      });
    this.saving = false;
  }

  close(): void {
    this.modal.hide();
    this.active = false;
  }
}
