import {Component, Input, OnDestroy, OnInit} from "@angular/core";
import {Option} from "../../../utils/indicator-utils";
import {AbstractControl} from "@angular/forms";
import {HelperFunctions} from "../../../openaireLibrary/utils/HelperFunctions.class";

@Component({
  selector: '[dashboard-input]',
  template: `
    <mat-form-field class="uk-width-1-1 uk-padding-remove">
      <input *ngIf="type === 'text'" matInput [placeholder]="label"
             [formControl]="formControl" [required]="required">
      <textarea *ngIf="type === 'textarea'" [rows]="rows" matInput [placeholder]="label" [formControl]="formControl"></textarea>
      <mat-select *ngIf="type === 'select'" [placeholder]="label" (openedChange)="stopPropagation()"
                  [formControl]="formControl" [disableOptionCentering]="true">
        <mat-option *ngFor="let option of options" [value]="option.value">
          {{option.label}}
        </mat-option>
      </mat-select>
    </mat-form-field>
  `
})
export class InputComponent implements OnInit, OnDestroy {
  @Input('formInput') formControl: AbstractControl;
  @Input('type') type: string = 'text';
  @Input('label') label: string;
  @Input('rows') rows: number = 3;
  @Input('options') options: Option[];
  private initValue: any;

  constructor() {
  }

  ngOnInit(): void {
    this.initValue = HelperFunctions.copy(this.formControl.value);
    this.formControl.valueChanges.subscribe(value => {
      if(this.initValue.toString() === value.toString()) {
        this.formControl.markAsPristine();
      }
    });
  }

  ngOnDestroy(): void {
  }

  public get required(): boolean {
    return this.formControl && this.formControl.validator
      && this.formControl.validator(this.formControl)
      && this.formControl.validator(this.formControl).required;
  }

  stopPropagation() {
    if(event) {
      event.stopPropagation();
    }
  }
}
