import { Directive, ElementRef, Renderer2, Input, OnChanges, SimpleChanges } from '@angular/core';
import { NgModel } from '@angular/forms';
import { AppService } from '../../core/services/app.service';

// tslint:disable-next-line: directive-selector
@Directive({ selector: 'input[resize]' })
export class InputResizeDirective implements OnChanges {
  @Input() ngModel: NgModel;

  get element(): HTMLInputElement {
    return this.elementRef.nativeElement;
  }

  constructor(private elementRef: ElementRef<HTMLInputElement>, private renderer: Renderer2, private appService: AppService) {}

  ngOnChanges({ ngModel }: SimpleChanges) {
    if (ngModel) {
      this.resize(this.element, String(ngModel.currentValue));
    }
  }

  resize(element: HTMLInputElement, value: string = this.element.value) {
    if (this.appService.isIPadEnv()) {
      return this.renderer.setStyle(element, 'width', this.calculatePxFromLength(value.length));
    }

    this.renderer.setAttribute(element, 'size', String(value.length || 1));
  }

  private calculatePxFromLength(length: number): string {
    const lengthMultiplier = 16;
    return String(Math.max(40, length * lengthMultiplier)) + 'px';
  }
}
