import { AbstractControl } from '@angular/forms';
import { EditorComponent } from '@tinymce/tinymce-angular';
import { debounceTime } from 'rxjs';

export class TinymceHelper {
  undoSubscription = null;
  constructor() {
  }

  public manageUndo(formControl: AbstractControl, tinyMce: EditorComponent) {
    if (this.undoSubscription !== null) {
      console.error('undoSubscription was already initialized!');
      return;
    }
    if (formControl && tinyMce) {
      this.undoSubscription = formControl.valueChanges.pipe(
        debounceTime(250)
      ).subscribe(
        text => {
          if (tinyMce?.editor?.undoManager) {
            tinyMce.editor.undoManager.beforeChange();
            tinyMce.editor.undoManager.add({
              // @ts-ignore
              type: 'complete',
              content: text
            });
          }
        }
      );
    }
  }

  public removeSubscriptionForUndo() {
    if (this.undoSubscription) {
      this.undoSubscription.unsubscribe();
      this.undoSubscription = null;
    }
  }
}

export class TinyMCEAttachments {
  public attachmentsApiService;
  blobsToReplace = {};
  attachmentsIDs = [];

  constructor(attachmentsApiService) {
    this.attachmentsApiService = attachmentsApiService;
  }

  appendAttachments(attachmentsIDs: string) {
    if (attachmentsIDs) {
      return `${attachmentsIDs}, ${this.getAttachmentsIDs()}`;
    } else {
      return this.getAttachmentsIDs();
    }
  }

  resetAttachments() {
    this.blobsToReplace = {};
    this.attachmentsIDs = [];
  }

  getAttachmentsIDs() {
    let att = '';
    for (const id of this.attachmentsIDs) {
      if (!att) {
        att = `${id}`;
      } else {
        att = `${att}, ${id}`;
      }
    }
    return att;
  }
}
