import {ChangeDetectorRef, Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ReplaySubject, Subscription} from 'rxjs';
import {ActivatedRoute, Router} from '@angular/router';
import {LayoutUtilsService, MessageType} from '../../../../../core/_base/crud';
import {ApiService} from '../../../../../core/api/api.service';
import {Vehiculos} from '../vehiculos.model';
import {MatTableDataSource} from '@angular/material';
import Utils from '../../../../../utils';

@Component({
  selector: 'kt-vehiculos-edit',
  templateUrl: './vehiculos-edit.component.html',
  styleUrls: ['./vehiculos-edit.component.scss']
})
export class VehiculosEditComponent implements OnInit {

   //Search
   typingTimer;
   typingInterval = 700;

   dataSourceTiposVehiculos: MatTableDataSource<any>;

   vehiculosForm: FormGroup;
   selectedTab = 0;
   subscriptions: Subscription[] = [];
   isNewVehiculo = false;
   isLoading = true;
   loading = false;
   vehiculoID = 0;
   recently = true;
   isLoadingInputSearch = true;

   filteredSucursales: ReplaySubject<any[]> = new ReplaySubject<any[]>(1);
   sucursales = [];

   filteredTiposVehiculos: ReplaySubject<any[]> = new ReplaySubject<any[]>(1);
   tipos_vehiculos = [];

   constructor(private fb: FormBuilder,
         private router: Router,
         private layoutUtilsService: LayoutUtilsService,
         private activatedRoute: ActivatedRoute,
         private ref: ChangeDetectorRef,
         private api: ApiService) {
         this.dataSourceTiposVehiculos = new MatTableDataSource<any>();
   }

   ngOnInit() {
     this.crearFormulario();
	 this.getTiposVehiculos();
	 this.getSucursales();
   }

   getVehiculo() {
     let routeSubscription = this.activatedRoute.params.subscribe(params => {
       this.vehiculoID = params.id;
       if (this.vehiculoID && this.vehiculoID > 0) {
          this.isNewVehiculo = false;
          this.api.vehiculos.show(this.vehiculoID).subscribe(res => {
          this.isLoading = false;
		  if(res.sucursales.length > 0){
			  res.sucursal_id = Utils.toNumber(res.sucursales[0].sucursal_id);
		  }
		  res.tipo_vehiculo_id = Utils.toNumber(res.tipo_vehiculo_id);

          this.vehiculosForm.reset(res);
          this.ref.detectChanges();
         });
       } else {
          this.isNewVehiculo = true;
          this.isLoading = false;
          this.ref.detectChanges();
       }
     });
     this.subscriptions.push(routeSubscription);
   }

   crearFormulario() {
     this.vehiculosForm = this.fb.group({
       num_economico: [null, [Validators.required, Validators.maxLength(128)]],
       descripcion: [null, [Validators.required, Validators.maxLength(128)]],
	   tipo_vehiculo_id: [null, [Validators.required, Validators.maxLength(128)]],
	   sucursal_id: [null, [Validators.required, Validators.maxLength(128)]],
	   searchSucursal: [''],
	   searchTipoVehiculo: [''],
     });
    }

   onSubmit() {
     let controls = this.vehiculosForm.controls;
	 let sucursalesArray = [];

     if (this.vehiculosForm.invalid) {
       Object.keys(controls).forEach(controlName => {
         controls[controlName].markAsTouched();
       })
       return;
     }

     let vehiculo : Vehiculos = this.vehiculosForm.value as Vehiculos;

	 sucursalesArray.push(this.vehiculosForm.value['sucursal_id']);
	 vehiculo.sucursales = sucursalesArray;

     if (this.isNewVehiculo) {
       this.addVehiculo(vehiculo);
     } else
       this.updateVehiculo(this.vehiculoID, vehiculo);
   }

	getSucursales() {
		this.api.vehiculos.sucursales('administrador/vehiculos/sucursales').subscribe(res => {
			this.sucursales = res;
			this.filteredSucursales.next(res.slice());
			this.ref.detectChanges();
		});
	}

	getTiposVehiculos() {
		this.api.vehiculos.tiposVehiculos('administrador/vehiculos/tipos_vehiculos').subscribe(res => {
			this.tipos_vehiculos = res.data;
			this.filteredTiposVehiculos.next(res.data.slice());
			this.ref.detectChanges();
		});
	}

	getTipoVehiculoFilter(query = null) {
		this.vehiculosForm.controls['searchTipoVehiculo'].setValue(query);
		if (query != '') {
			this.api.vehiculos.tiposVehiculos('administrador/vehiculos/tipos_vehiculos?query=' + query).subscribe(res => {
				this.filteredTiposVehiculos.next(res.data.slice());
				this.isLoadingInputSearch = false;
				this.ref.detectChanges();
			});
		}
	}

	getSucursalFilter(query = null) {
		this.vehiculosForm.controls['searchSucursal'].setValue(query);
		if (query != '') {
			this.api.vehiculos.sucursales('administrador/vehiculos/sucursales?query=' + query).subscribe(res => {
				this.filteredSucursales.next(res.slice());
				this.isLoadingInputSearch = false;
				this.ref.detectChanges();
			});
		}
	}

	onKeyUpManual(ev, tipo) {
		let text = ev.target.value;

		if (text != '') {
			this.recently = false;
		}

		if (!this.recently) {
			this.isLoadingInputSearch = true;
			clearTimeout(this.typingTimer);
			this.typingTimer = setTimeout(() => {

				switch (tipo) {
					case 'sucursal_id': {
						this.getSucursalFilter(text);
						break;
					}
					case 'tipo_vehiculo': {
						this.getTipoVehiculoFilter(text);
						break;
					}
				}

				if (text == '') {
					this.recently = true;
				}

			}, this.typingInterval);
		} else {
			this.isLoadingInputSearch = false;
		}

	}

	onKeyDown(tipo) {
		this.isLoadingInputSearch = false;

		switch (tipo) {
			case 'sucursal_id': {
				this.filteredSucursales.next([]);
				break;
			}
			case 'tipo_vehiculo': {
				if (!this.recently)
					this.filteredTiposVehiculos.next([]);
				break;
			}
		}

		clearTimeout(this.typingTimer);
	}

	changeNoFoundLabel() {
		return this.isLoadingInputSearch ? 'Espere un momento...' : 'No se encontraron resultados';
	}

   addVehiculo(vehiculo) {
     this.api.vehiculos.create(vehiculo).subscribe(() => {
       this.loading = false;
       this.layoutUtilsService.showActionNotification('Vehículo guardado con éxito.', MessageType.Create);
       this.router.navigate(['../'], {relativeTo: this.activatedRoute})
     }, () => {
       this.loading = false;
     });
   }

   updateVehiculo(id, vehiculo) {
     this.api.vehiculos.update(id, vehiculo).subscribe(() => {
       this.loading = false;
       this.layoutUtilsService.showActionNotification('Vehículo actualizado con éxito.', MessageType.Update);
       this.router.navigate(['../../'], {relativeTo: this.activatedRoute})
     }, () => {
       this.loading = false;
     });
   }

   isControlValid(controlName: string): boolean {
     let control = this.vehiculosForm.controls[controlName];
     if (!control) {
       return false;
     } else if (control.valid) {
       return false;
     }
     return true;
   }

   isControlHasError(controlName: string, validationType: string): boolean {
     let control = this.vehiculosForm.controls[controlName];
     if (!control) {
       return false;
     }
     return control.hasError(validationType) && (control.dirty || control.touched);
   }

   ngAfterViewInit(): void {
     this.getVehiculo();
   }

}
