import {
  Component,
  ChangeDetectionStrategy,
  Input,
  OnChanges,
  SimpleChanges,
  Output,
  EventEmitter,
  ChangeDetectorRef,
} from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-shelf-order-details-comment',
  templateUrl: 'comment.component.html',
  styleUrls: ['comment.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ShelfOrderDetailsCommentComponent implements OnChanges {
  focused: boolean;

  @Input()
  comment: string;

  commentControl = new FormControl(undefined);

  @Output()
  saveComment = new EventEmitter<string>();

  constructor(private cdr: ChangeDetectorRef) {}

  ngOnChanges({ comment }: SimpleChanges): void {
    if (comment) {
      this.commentControl.reset(comment.currentValue);
      this.commentControl.disable();
      this.cdr.markForCheck();
    }
  }

  save() {
    this.saveComment.emit(this.commentControl.value);
  }

  inputFocus() {
    this.focused = true;
  }

  inputBlur() {
    setTimeout(() => {
      this.focused = false;
      this.cdr.markForCheck();
    }, 500);
  }
}
