import { Component, OnInit, Input, ViewChild, Output, EventEmitter } from '@angular/core';
import { Annotation, NgxAnnotateTextComponent } from 'ngx-annotate-text';
import { CommonServiceLayerService, RequestPayLoadFormat } from 'src/app/services/common-service-layer.service';
import { SessionService } from 'src/app/services/session.service';
import { ToastrService } from '../toastr/toastr.service';

@Component({
  selector: 'app-annotate-text',
  templateUrl: './annotate-text.component.html',
  styleUrls: ['./annotate-text.component.scss']
})
export class AnnotateTextComponent implements OnInit {
  @ViewChild("annotateText") ngxAnnotateText?: NgxAnnotateTextComponent;
  @Input() inputData;
  @Output() closePopup = new EventEmitter();
  @Output() saveData = new EventEmitter();
  annotations: Annotation[] = [];
  showAddTag = true;
  tagsList;
  selectedTag;
  constructor(
    private _toast: ToastrService,
    private http: CommonServiceLayerService,
    private session: SessionService
  ) {

  }

  ngOnInit(): void {
    this.inputData.annotation_details.forEach((e) => {
      this.annotations = this.annotations.concat(
        new Annotation(
          e.startIndex,
          e.endIndex,
          e.tag,
          "#499bbc"
        )
      );
    });
  }
  /**
   * Method to handle text selection and annotation addition.
   */
  addAnnotation(label: string): void {
    if (!this.ngxAnnotateText) {
      return;
    }
    const selection = this.ngxAnnotateText.getCurrentTextSelection();
    if (!selection) {
      return;
    }

    if (this.ngxAnnotateText.isOverlappingWithExistingAnnotations(selection)) {
      alert("The selected text is already annotated.");
      return;
    }
    if (selection.endIndex - selection.startIndex <= 128) {
      this.annotations = this.annotations.concat(
        new Annotation(selection.startIndex, selection.endIndex, label, '#499bbc')
      );
    } else {
      this._toast.toast('warning', 'Warning', 'Selected text is too big to be tagged.', true);

    }
  }
  /**
   * Method to put annotations into JSON format and emit to parent.
   */
  saveAnnotations() {
    try {
      this.inputData.annotation_details = [];
      this.annotations.forEach(element => {
        this.inputData.annotation_details = this.inputData.annotation_details.concat({
          "startIndex": element.startIndex,
          "endIndex": element.endIndex,
          "tag": element.label,
          "keyword": this.inputData.text.substring(element.startIndex, element.endIndex)
        })
      });
      this.saveData.emit(this.inputData);
    } catch (error) {
      console.log(error);
    }
  }
  /**
   * Method to get new tags.
   */
  showNewTags() {
    try {
      const request: RequestPayLoadFormat = {
        api: 'TAGS_LIST',
        // method: 'post',
        // type: 'API',
        method: 'get',
        type: 'JSON',
        loader: true,
        payLoad: {},
        hideErrorMessage: false
      };

      this.tagsList = [];
      this.http.API_REQUEST(request).subscribe((response) => {
        if (response.status === 'SUCCESS' && response.data) {
          this.tagsList = response.data;
          this.showAddTag = false;
        } else {
          this._toast.toast('warning', 'Warning', response.message || 'Error while Loading data.', true);
        }
      });
    } catch (error) {
      console.log(error);
    }
  }
  addTag() {
    try {
      let i = this.tagsList.findIndex((e) => e.value === this.selectedTag);
      this.inputData.class_details.push(this.tagsList[i].label);
      this.showAddTag = true;
      this.selectedTag = null;
    } catch (error) {
      console.log(error);
    }
  }
  closePopupEmitter() {
    try {
      this.closePopup.emit(true);
    } catch (error) {
      console.log(error);
    }
  }
}
