import {ChangeDetectorRef, Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Subscription} from 'rxjs';
import {ActivatedRoute, Router} from '@angular/router';
import {LayoutUtilsService, MessageType} from '../../../../../core/_base/crud';
import {ApiService} from '../../../../../core/api/api.service';
import {TiposVehiculo} from '../tipos-vehiculo.model';

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

  //SearchRols
  typingTimerRol;
  typingIntervalRol = 700;
  searchTextRol: string = '';
  lastLengthRol = 0;
  hidePassword = true;

  tiposVehiculoForm: FormGroup;
  selectedTab = 0;
  subscriptions: Subscription[] = [];
  isNewTiposVehiculo = false;
  isLoading = true;
  loading = false;
  tiposVehiculoID = 0;

  constructor(private fb: FormBuilder,
        private router: Router,
        private layoutUtilsService: LayoutUtilsService,
        private activatedRoute: ActivatedRoute,
        private ref: ChangeDetectorRef,
        private api: ApiService) {
  }

  ngOnInit() {
    this.crearFormulario();
  }

  getTiposVehiculo() {
    let routeSubscription = this.activatedRoute.params.subscribe(params => {
      this.tiposVehiculoID = params.id;
      if (this.tiposVehiculoID && this.tiposVehiculoID > 0) {
        this.isNewTiposVehiculo = false;
        this.api.tiposVehiculos.show(this.tiposVehiculoID).subscribe(res => {
        this.isLoading = false;
        this.tiposVehiculoForm.reset(res);
        this.ref.detectChanges();
        });
      } else {
        this.isNewTiposVehiculo = true;
        this.isLoading = false;
        this.ref.detectChanges();
      }
    });
    this.subscriptions.push(routeSubscription);
  }

  crearFormulario() {
    this.tiposVehiculoForm = this.fb.group({
      nombre: [null, [Validators.required, Validators.maxLength(128)]],
      objetivo_mensual: [null, [Validators.maxLength(128), Validators.pattern("^[0-9]*$"), Validators.minLength(1), Validators.maxLength(10)]],
    });	
  }

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

    let tiposVehiculo : TiposVehiculo = this.tiposVehiculoForm.value as TiposVehiculo;

    if (this.isNewTiposVehiculo) {
      this.addTiposVehiculo(tiposVehiculo);
    } else
      this.updateTiposVehiculo(this.tiposVehiculoID, tiposVehiculo);
  }

  addTiposVehiculo(formaPago) {
    this.api.tiposVehiculos.create(formaPago).subscribe(() => {
      this.loading = false;
      this.layoutUtilsService.showActionNotification('Tipo de vehículo guardado con éxito.', MessageType.Create);
      this.router.navigate(['../'], {relativeTo: this.activatedRoute})
    }, () => {
      this.loading = false;
    });
  }

  updateTiposVehiculo(id, tiposVehiculo) {
    this.api.tiposVehiculos.update(id, tiposVehiculo).subscribe(() => {
      this.loading = false;
      this.layoutUtilsService.showActionNotification('Tipo de vehículo actualizado con éxito.', MessageType.Update);
      this.router.navigate(['../../'], {relativeTo: this.activatedRoute})
    }, () => {
      this.loading = false;
    });
  }

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

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

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