import { Component, Output, ViewChild, EventEmitter, Input, ElementRef, HostListener } from '@angular/core';
import { UntypedFormGroup,UntypedFormBuilder, Validators } from '@angular/forms';
import { IListItem } from '@farmmaps/common';
import { IDroppedFile } from '../aol/file-drop-target/file-drop-target.component';
import {NgbModal, NgbModalRef} from "@ng-bootstrap/ng-bootstrap";

export interface IMetaData {
  droppedFile: IDroppedFile,
  attributes: any
}

@Component({
  selector: 'fm-map-meta-data-modal',
  templateUrl: 'meta-data-modal.component.html'
})
export class MetaDataModalComponent {

  private modalName = 'metaDataModal';
  private modalRef: NgbModalRef;

  @ViewChild('content', { static: true }) _templateModal:ElementRef;
  @Input() droppedFile: IDroppedFile;
  @Input() set modalState(_modalState:any) {
    if(_modalState == this.modalName) {
      this.openModal()
    } else if(this.modalRef) {
      this.closeModal();
    }
  }

  @Input() event: IListItem;

  @Output() onCloseModal = new EventEmitter<any>();
  @Output() onAddFilesWithMetaData = new EventEmitter<IMetaData>();

  constructor(private modalService: NgbModal, public fb: UntypedFormBuilder) { }

  public metaDataForm: UntypedFormGroup;

  handleMetaDataEntered(event) {
    if (this.metaDataForm.valid) {
      this.onAddFilesWithMetaData.emit({ droppedFile: this.droppedFile, attributes: { name: this.metaDataForm.value.name } });
    }
  }

  openModal() {
      //Timeout trick to avoid ExpressionChangedAfterItHasBeenCheckedError 
      setTimeout(() => this.modalRef = this.modalService.open(this._templateModal, { backdrop: 'static', keyboard: false }));     
  }  

  closeModal()  {
      this.modalRef.close();
      this.metaDataForm.patchValue({ name: "" });
  }

   ngOnInit(): void {
      this.metaDataForm = this.fb.group({
      name: ["", Validators.compose([Validators.required, Validators.pattern("[a-zA-Z0-9_].*")])]
      });
  }
}
