import {
  Component,
  OnInit,
  Output,
  EventEmitter,
  ViewChild,
  ElementRef,
  Input
} from '@angular/core';
import { NgForm } from '@angular/forms';
import { FileUploadItem } from '@ucap-webmessenger/api-common';
import { FileUploadQueueComponent } from '@ucap-webmessenger/ui';

@Component({
  selector: 'ucap-chat-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit {
  @Input()
  fileUploadQueue: FileUploadQueueComponent;

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

  @Output()
  sendFiles = new EventEmitter<FileUploadItem[]>();

  @Output()
  toggleStickerSelector = new EventEmitter<void>();

  @Output()
  clearView = new EventEmitter();

  @ViewChild('replyForm', { static: false })
  replyForm: NgForm;

  @ViewChild('replyInput', { static: false })
  replyInput: ElementRef<HTMLTextAreaElement>;

  @ViewChild('fileInput', { static: false })
  fileInput: ElementRef<HTMLInputElement>;

  constructor() {}

  ngOnInit() {}

  focus(): void {
    this.replyInput.nativeElement.focus();
  }

  onSend(event: Event) {
    event.preventDefault();

    this.send.emit(this.replyForm.form.value.message);
    this.replyForm.reset();
  }

  onClickFileInput() {
    this.clearView.emit();
    this.fileInput.nativeElement.click();
  }

  onChangeFileInput() {
    const fileUploadItems = FileUploadItem.fromFiles(
      this.fileInput.nativeElement.files
    );

    if (!!this.fileUploadQueue) {
      this.fileUploadQueue.onFileSelected(fileUploadItems);
    }

    this.sendFiles.emit(fileUploadItems);

    this.fileInput.nativeElement.value = '';
  }

  onClickStickerSelector() {
    this.toggleStickerSelector.emit();
  }
}
