import {
  Component,
  ChangeDetectionStrategy,
  EventEmitter,
  ViewChild,
  ElementRef,
  ChangeDetectorRef,
  forwardRef,
  Output,
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'page-special-comment',
  templateUrl: 'special-comment.component.html',
  styleUrls: ['special-comment.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => SpecialCommentComponent), multi: true }],
})
export class SpecialCommentComponent implements ControlValueAccessor {
  private initialValue = '';
  value = '';

  valueChange = new EventEmitter<string>();

  disabled = false;

  private onChange = (value: string) => {};

  private onTouched = () => {};

  rows = 1;

  isDirty = false;

  @Output()
  isDirtyChange = new EventEmitter<boolean>();

  constructor(private readonly cdr: ChangeDetectorRef) {}

  writeValue(obj: any): void {
    this.value = obj ?? '';
    this.initialValue = obj ?? '';
    this.check();
    this.cdr.markForCheck();
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

  setDisabledState?(isDisabled: boolean): void {
    this.disabled = isDisabled ?? this.disabled;
    this.check();
    this.cdr.markForCheck();
  }

  clear() {
    this.value = '';
    this.save();
  }

  check() {
    this.onTouched();
    this.checkIsDirty();
    this.checkRows();
  }

  checkIsDirty() {
    this.setIsDirty(this.initialValue !== this.value);
    this.cdr.markForCheck();
  }

  checkRows() {
    this.rows = this.value.split(/\r*\n/).length || 1;
    this.cdr.markForCheck();
  }

  save() {
    this.initialValue = this.value;
    this.onChange(this.value);
    this.check();
  }
  setIsDirty(isDirty: boolean) {
    this.isDirty = isDirty;
    this.isDirtyChange.emit(isDirty);
  }
}
