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 {Servicios} from '../servicios.model';


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

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

  serviciosForm: FormGroup;
  selectedTab = 0;
  subscriptions: Subscription[] = [];
  isNewServicio = false;
  isLoading = true;
  loading = false;
  servicioID = 0;

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

  ngOnInit() {
    this.crearFormulario();
  }

  getServicios() {
    let routeSubscription = this.activatedRoute.params.subscribe(params => {
      this.servicioID = params.id;
      if (this.servicioID && this.servicioID > 0) {
        this.isNewServicio = false;
        this.api.servicios.show(this.servicioID).subscribe(res => {
          this.isLoading = false;
          this.serviciosForm.reset(res);
          this.ref.detectChanges();
        });
      } else {
        this.isNewServicio = true;
        this.isLoading = false;
        this.ref.detectChanges();
      }
    });
    this.subscriptions.push(routeSubscription);
  }

  crearFormulario() {
    this.serviciosForm = this.fb.group({
      nombre: [null, [Validators.required, Validators.maxLength(128)]],
    });	}

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

    let servicio : Servicios = this.serviciosForm.value as Servicios;

    if (this.isNewServicio) {
      this.addServicio(servicio);
    } else
      this.updateServicio(this.servicioID, servicio);
  }

  addServicio(servicio) {
    this.api.servicios.create(servicio).subscribe(() => {
      this.loading = false;
      this.layoutUtilsService.showActionNotification('Servicio guardado con éxito.', MessageType.Create);
      this.router.navigate(['../'], {relativeTo: this.activatedRoute})
    }, () => {
      this.loading = false;
    });
  }

  updateServicio(id, servicio) {
    this.api.servicios.update(id, servicio).subscribe(() => {
      this.loading = false;
      this.layoutUtilsService.showActionNotification('Servicio actualizado con éxito.', MessageType.Update);
      this.router.navigate(['../../'], {relativeTo: this.activatedRoute})
    }, () => {
      this.loading = false;
    });
  }

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

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

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

}
