import { Directive, ElementRef, HostListener, Input, Renderer2 } from '@angular/core';

@Directive({
  selector: '[inputPassword2Text]',
  exportAs: 'inputPassword2Text'
})
export class InputPassword2TextDirective {
  @Input('inputPassword2Text') model: HTMLInputElement | HTMLInputElement[] = undefined;

  constructor(private renderer: Renderer2,
              private elementRef: ElementRef) {
  }

  @HostListener('click', [ '$event' ])
  onClick(event: MouseEvent): void {
    if (!this.model) {
      return;
    }

    if (Array.isArray(this.model)) {
      this.model.forEach((model: HTMLInputElement) => this.trigger(model));
    } else {
      this.trigger(this.model);
    }
  }

  trigger(model: HTMLInputElement): void {
    const type: string = model.type;
    switch (type) {
      case 'password':
        this.renderer.setProperty(model, 'type', 'text');
        this.renderer.setAttribute(model, 'type', 'text');
        break;
      case 'text':
        this.renderer.setProperty(model, 'type', 'password');
        this.renderer.setAttribute(model, 'type', 'password');
        break;
      default:
    }
  }
}
