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[]>();

  @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.fileInput.nativeElement.click();
  }

  onChangeFileInput() {
    const files: File[] = [];
    for (let i = 0; i < this.fileInput.nativeElement.files.length; i++) {
      files.push(this.fileInput.nativeElement.files.item(i));
    }

    const fileUploadItems = FileUploadItem.fromFiles(files);

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

    this.sendFiles.emit(fileUploadItems);
  }
}