import { Component, EventEmitter, Input, Output } from '@angular/core';
import { ThemePalette } from '@angular/material/core';

@Component({
  selector: 'app-dynamic-input',
  templateUrl: './dynamic-input.component.html',
  styleUrls: ['./dynamic-input.component.css']
})
export class DynamicInputComponent {

  @Output() dataValue: EventEmitter<string | Array<any> | boolean> = new EventEmitter();

  @Input() label:string;
  @Input() tag:string;
  @Input() type:string;
  @Input() placeholder:string;
  @Input() value: string | Array<any> | boolean;
  @Input() id:string;
  @Input() name: string;
  @Input() required: boolean;
  @Input() readonly: boolean;
  @Input() maxLength: string;
  @Input() pattern: string;
  @Input() disabled: boolean;
  @Input() accept_file: string;
  @Input() icon: string;
  @Input() column: string;

  public colorState: ThemePalette;

  constructor() {
    this.label = '';
    this.tag = '';
    this.type = '';
    this.placeholder = '';
    this.value = '';
    this.id = '';
    this.name = '';
    this.required = false;
    this.readonly = false;
    this.maxLength = '';
    this.pattern = '';
    this.disabled = false;
    this.accept_file = '';
    this.icon = '';
    this.column = '';
    this.colorState = 'primary'
  }

  public getFile() {
    document.getElementById(this.id)!!.click();
  }

  public sub(obj: any) {
    var file = obj.value;
    if (file != '') {
      var fileName = file.split("\\");
      document.getElementById("yourBtn")!!.innerHTML = fileName[fileName.length - 1];
    } else {
      document.getElementById("yourBtn")!!.innerHTML = "Click aquí para subir un archivo";
    }
  }

  public setValue(event:any) {
    let dataInput:string = (event.target as HTMLInputElement).value;
    this.dataValue.emit( dataInput );
  }

  public validatorData(textValue:string, pattern:string, required:boolean) {
    let dataValidate = new RegExp(pattern);
    return dataValidate.test(textValue) && (textValue !== '' && required);
  }

}
