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 {TiposServicio} from '../tipos-servicio.model';

@Component({
  selector: 'kt-tipos-servicio-edit',
  templateUrl: './tipos-servicio-edit.component.html',
  styleUrls: ['./tipos-servicio-edit.component.scss']
})
export class TiposServicioEditComponent implements OnInit {
  //SearchRols
  typingTimerRol;
  typingIntervalRol = 700;
  searchTextRol: string = '';
  lastLengthRol = 0;
  hidePassword = true;

  tiposServicioForm: FormGroup;
  selectedTab = 0;
  subscriptions: Subscription[] = [];
  isNewTiposServicio = false;
  isLoading = true;
  loading = false;
  tiposServicioID = 0;

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

  ngOnInit() {
    this.crearFormulario();
  }

  getTiposServicio() {
    let routeSubscription = this.activatedRoute.params.subscribe(params => {
      this.tiposServicioID = params.id;
      if (this.tiposServicioID && this.tiposServicioID > 0) {
        this.isNewTiposServicio = false;
        this.api.tiposServicio.show(this.tiposServicioID).subscribe(res => {
          this.isLoading = false;
          this.tiposServicioForm.reset(res);
          this.ref.detectChanges();
        });
      } else {
        this.isNewTiposServicio = true;
        this.isLoading = false;
        this.ref.detectChanges();
      }
    });
    this.subscriptions.push(routeSubscription);
  }

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

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

    let tiposServicio : TiposServicio = this.tiposServicioForm.value as TiposServicio;

    if (this.isNewTiposServicio) {
      this.addTiposServicio(tiposServicio);
    } else
      this.updateTiposServicio(this.tiposServicioID, tiposServicio);
  }

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

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

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

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

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

}
