import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import * as reserved_words from 'src/assets/json/reserved_words.json';
import * as data from 'src/assets/json/icons.json';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';

@Component({
  selector: 'app-configure-input',
  templateUrl: './configure-input.component.html',
  styleUrls: ['./configure-input.component.css'],
})
export class ConfigureInputComponent implements OnInit {
  public formGroup: FormGroup;
  public num_cols: number;
  public arr_columns: Array<string>;
  public arr_icons: Array<any> = [];
  filteredOptions!: Observable<string[]>;

  constructor(
    public dialogRef: MatDialogRef<ConfigureInputComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    this.num_cols = data.num_cols;
    this.arr_columns = data.column;
    this.formGroup = this.createFormGroup();
  }

  ngOnInit(): void {
    let data_icons = data;
    this.arr_icons = data_icons.icons;
    let arr_icons_aux: any = [];

    this.arr_icons.map((element) => {
      if (!arr_icons_aux.includes(element.name)) {
        arr_icons_aux.push(element.name);
      }
    });
    this.arr_icons = arr_icons_aux;

    this.filteredOptions = this.formGroup.controls['icon'].valueChanges.pipe(
      startWith(''),
      map(value => this._filter(value || '')),
    );
  }

  private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();
    return this.arr_icons.filter(option => option.toLowerCase().includes(filterValue));
  }

  private createFormGroup() {
    return new FormGroup({
      tag: new FormControl('input', Validators.required),
      column: new FormControl('', Validators.required),
      name: new FormControl('', Validators.required),
      id: new FormControl('', [Validators.required, this.applyFilterControl]),
      type: new FormControl('text', Validators.required),
      placeholder: new FormControl(''),
      label: new FormControl('', Validators.required),
      max: new FormControl(45, Validators.required),
      value: new FormControl(''),
      pattern: new FormControl(),
      msgerror: new FormControl({ value: '', disabled: true}),
      icon: new FormControl(''),
      disabled_reg: new FormControl(false),
      disabled_mod: new FormControl(false),
      required_reg: new FormControl(false),
      required_mod: new FormControl(false),
      readonly_reg: new FormControl(false),
      readonly_mod: new FormControl(false),
      deleted: new FormControl(true),
      num_col: new FormControl(1, Validators.required),
      num_row: new FormControl(1, Validators.required),
    });
  }

  public numColumn(type: string) {
    if (type == 'add') {
      if (this.formGroup.controls['num_col'].value + 1 <= this.num_cols) {
        this.formGroup.controls['num_col'].setValue(this.formGroup.controls['num_col'].value + 1);
      }
    } else {
      if (this.formGroup.controls['num_col'].value - 1 >= 1) {
        this.formGroup.controls['num_col'].setValue(this.formGroup.controls['num_col'].value - 1);
      }
    }
  }

  public applyFilterControl(control: any) {
    const filterValue = control.value;
    let arrWords = reserved_words;
    let filter = arrWords.reserved_words.filter(
      (element: string) => element == filterValue.trim().toUpperCase()
    );
    if (filter.length > 0) {
      return {
        validWords: {
          word: filterValue,
        },
      };
    }

    return null;
  }

  public changeColumn() {
    let text_column = this.formGroup.controls['column'].value;
    this.formGroup.controls['name'].setValue(text_column);
    this.formGroup.controls['id'].setValue(text_column);
  }

  public changeType() {
    let type_input = this.formGroup.controls['type'].value;
    if (type_input === 'file') {
      this.formGroup.controls['placeholder'].disable();
      this.formGroup.controls['value'].disable();
      this.formGroup.controls['max'].disable();
      this.formGroup.controls['max'].setValue(0);
      this.formGroup.controls['pattern'].disable();
      this.formGroup.controls['msgerror'].disable();
      this.formGroup.controls['readonly_reg'].disable();
      this.formGroup.controls['readonly_mod'].disable();
      this.formGroup.controls['disabled_reg'].disable();
      this.formGroup.controls['disabled_mod'].disable();
      this.formGroup.controls['icon'].setValue('file_upload');
    } else {
      this.formGroup.controls['placeholder'].enable();
      this.formGroup.controls['value'].enable();
      this.formGroup.controls['max'].enable();
      this.formGroup.controls['max'].setValue(0);
      this.formGroup.controls['pattern'].enable();
      this.formGroup.controls['msgerror'].enable();
      this.formGroup.controls['readonly_reg'].enable();
      this.formGroup.controls['readonly_mod'].enable();
      this.formGroup.controls['disabled_reg'].enable();
      this.formGroup.controls['disabled_mod'].enable();
      this.formGroup.controls['icon'].setValue('');
    }
  }


  public validPattern(textPattern:string) {
    if (textPattern === '') {
      this.formGroup.controls['msgerror'].disable();
      this.formGroup.controls['msgerror'].clearValidators();
    }else{
      this.formGroup.controls['msgerror'].enable();
      this.formGroup.controls['msgerror'].setValidators(Validators.required);
      this.formGroup.controls['msgerror'].setValue('');
    }
  }
}
