import {
  ChangeDetectorRef,
  Component,
  EventEmitter,
  forwardRef,
  Input,
  Output,
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { ControlContainer, NgForm } from '@angular/forms';
import { UuidUtils } from '../../utilities/uuid-utils';

@Component({
  selector: 'rbj-password-input',
  templateUrl: './password-input.component.html',
  styleUrl: './password-input.component.scss',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => PasswordInputComponent),
      multi: true,
    },
  ],
  viewProviders: [{ provide: ControlContainer, useExisting: NgForm }],
})
export class PasswordInputComponent implements ControlValueAccessor {
  private _value = '';
  disabledState = false;
  uuid: string = UuidUtils.generate();
  /**
   *
   */
  constructor(
    private cdRef: ChangeDetectorRef,
  ) {

  }
  @Input() id = '';
  @Input() placeholder = 'Passphrase';
  text: string = '';


  onChange = (value: string) => { };
  onTouched = () => { };
  @Output() blur = new EventEmitter<string>();

  fieldTextType = false;

  toggleFieldTextType(): void {
    this.fieldTextType = !this.fieldTextType;
  }

  writeValue(value: string): void {
    if (value != this.lastBlurValue) {
      this.text = value;
      this.lastBlurValue = value;
    }
  }

  registerOnChange(fn: (value: string) => void): void {
    this.onChange = fn;
  }
  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

  setDisabledState(isDisabled: boolean): void {
    this.disabledState = isDisabled;
  }

  lastBlurValue: string = '';
  onBlur() {
    if (this.lastBlurValue != this.text) {
      this.lastBlurValue = this.text;
      this.blur.emit(this.text);
    }
  }
}
