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

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

sucursalesForm: FormGroup;
selectedTab = 0;
subscriptions: Subscription[] = [];
isNewSucursal = false;
isLoading = true;
loading = false;
sucursalID = 0;

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

ngOnInit() {
  this.crearFormulario();
}

getSucursales() {
  let routeSubscription = this.activatedRoute.params.subscribe(params => {
    this.sucursalID = params.id;
    if (this.sucursalID && this.sucursalID > 0) {
      this.isNewSucursal = false;
      this.api.sucursales.show(this.sucursalID).subscribe(res => {
        this.isLoading = false;
        this.sucursalesForm.reset(res);
        this.ref.detectChanges();
      });
    } else {
      this.isNewSucursal = true;
      this.isLoading = false;
      this.ref.detectChanges();
    }
  });
  this.subscriptions.push(routeSubscription);
}

crearFormulario() {
  this.sucursalesForm = this.fb.group({
    nombre: [null, [Validators.required, Validators.maxLength(128)]],
    calle: [null, [Validators.required, Validators.maxLength(128)]],
    num_ext: [null, [Validators.required, Validators.maxLength(128)]],
    num_int: [null, [Validators.maxLength(128)]],
    colonia: [null, [Validators.required, Validators.maxLength(128)]],
    cp: [null, [Validators.required, Validators.maxLength(128)]],
    telefono: [null, [Validators.required, Validators.maxLength(128)]],
    gerente: [null, [Validators.required, Validators.maxLength(128)]],
    encargado: [null, [Validators.required, Validators.maxLength(128)]],
  });	}

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

  let sucursal : Sucursales = this.sucursalesForm.value as Sucursales;

  if (this.isNewSucursal) {
    this.addSucursal(sucursal);
  } else
    this.updateSucursal(this.sucursalID, sucursal);
}

addSucursal(sucursal) {
  this.api.sucursales.create(sucursal).subscribe(() => {
    this.loading = false;
    this.layoutUtilsService.showActionNotification('Sucursal guardada con éxito.', MessageType.Create);
    this.router.navigate(['../'], {relativeTo: this.activatedRoute})
  }, () => {
    this.loading = false;
  });
}

updateSucursal(id, sucursal) {
  this.api.sucursales.update(id, sucursal).subscribe(() => {
    this.loading = false;
    this.layoutUtilsService.showActionNotification('Sucursal actualizada con éxito.', MessageType.Update);
    this.router.navigate(['../../'], {relativeTo: this.activatedRoute})
  }, () => {
    this.loading = false;
  });
}

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

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

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