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 {ClientesDomicilios} from '../clientes-domicilios.model';
import {environment} from '../../../../../../environments/environment';

@Component({
  selector: 'kt-clientes-domicilios-edit',
  templateUrl: './clientes-domicilios-edit.component.html',
  styleUrls: ['./clientes-domicilios-edit.component.scss']
})

export class ClientesDomiciliosEditComponent implements OnInit {

domiciliosForm: FormGroup;
selectedTab = 0;
subscriptions: Subscription[] = [];
isNewDomicilio = false;
isLoading = true;
loading = false;
domicilioID = 0;
clienteID = '';
informacionID = '';
base64textStringSketch;
fileName = '';

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

  ngOnInit() {
    this.crearFormulario();
    this.clienteID = this.activatedRoute.snapshot.paramMap.get('clienteDomicilioID');
  }

  getDomicilios() {
    let routeSubscription = this.activatedRoute.params.subscribe(params => {
      this.domicilioID = params.id;
      if (this.domicilioID && this.domicilioID > 0) {
        this.isNewDomicilio = false;
        this.api.clientesDomicilios.show('/domicilios', this.domicilioID, this.clienteID).subscribe(res => {
          this.isLoading = false;
		  this.fileName = res.nombre_croquis;
          this.domiciliosForm.reset(res);
          this.ref.detectChanges();
        });
      } else {
        this.isNewDomicilio = true;
        this.isLoading = false;
        this.ref.detectChanges();
      }
    });
    this.subscriptions.push(routeSubscription);
  }

  crearFormulario() {
    this.domiciliosForm = this.fb.group({
      nombre_sucursal: [null, [Validators.required, Validators.maxLength(128)]],
      numero_sucursal: [null, [Validators.required, Validators.maxLength(128)]],
      email: [null, [Validators.maxLength(128), Validators.email]],
      calle: [null, [Validators.required, Validators.maxLength(128)]],
      entre_calles: [null, [Validators.maxLength(128)]],
      num_ext: [null, [Validators.required, Validators.maxLength(128)]],
      num_int: [null, [Validators.maxLength(128)]],
      colonia: [null, [Validators.required, Validators.maxLength(128)]],
      ciudad: [null, [Validators.required, Validators.maxLength(128)]],
      cp: [null, [Validators.required, Validators.maxLength(128)]],
      telefono: [null, [Validators.required, Validators.maxLength(128)]],
      nombre_responsable_sucursal: [null, [Validators.required, Validators.maxLength(128)]],
      celular_responsable: [null, [Validators.required, Validators.maxLength(128)]],
	  nombre_croquis: []
    });
  }

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

    let domicilio : ClientesDomicilios = this.domiciliosForm.value as ClientesDomicilios;
	domicilio.nombre_croquis = this.base64textStringSketch;

    if (this.isNewDomicilio) {
      this.addDomicilio(domicilio);
    } else
      this.updateDomicilio(this.domicilioID, domicilio);
  }

  addDomicilio(domicilio) {
    this.api.clientesDomicilios.create('/domicilios', domicilio, this.clienteID).subscribe(() => {
      this.loading = false;
      this.layoutUtilsService.showActionNotification('Domicilio actualizado con éxito.', MessageType.Create);
      this.router.navigate(['../../../clientes-domicilios/', this.clienteID], {relativeTo: this.activatedRoute})
    }, () => {
      this.loading = false;
    });
  }

  updateDomicilio(id, domicilio) {
    this.api.clientesDomicilios.update('/domicilios',id, domicilio, this.clienteID).subscribe(() => {
      this.loading = false;
      this.layoutUtilsService.showActionNotification('Domicilio actualizado con éxito.', MessageType.Update);
      this.router.navigate(['../../../../clientes-domicilios/', this.clienteID], {relativeTo: this.activatedRoute})
    }, () => {
      this.loading = false;
    });
  }

openPDF(domicilioId) {
	window.open(environment.API + `administrador/clientes/domicilios/${domicilioId}?token=`+this.api.getAccessToken(), '_blank');
}

handleUpload(event) {
	const file = event.target.files[0];
	this.fileName = file.name;

	if(file.size > 5000000){
		this.api.snackbar('PDF demasiado grande')
		return;
	}

	if(file){
		const reader = new FileReader();
		reader.onload = this.readerLoadedSketch.bind(this);
		reader.readAsDataURL(file);
	}
}

readerLoadedSketch(readerEvt) {
	this.base64textStringSketch = readerEvt.target.result;
}

reset(){
	this.fileName = null;
	this.base64textStringSketch = null;
}

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

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

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