// Angular Core
import { Injectable } from '@angular/core';

// Services
import { Subject } from 'rxjs';
import { ModalServiceConfig } from 'src/app/interfaces/modal-interface';

@Injectable({
  providedIn: 'root'
})
export class TrxademodalService {
  /* Array to hold modals that are sent by different components. */
  private modalComponents: Array<ModalServiceConfig> = [];

  /* A modal picked to process from the modal pipe */
  private currentModal!: ModalServiceConfig | undefined;

  /* Observable to receive the modal config object sent by different components */
  public modalPipe: Subject<ModalServiceConfig> = new Subject<ModalServiceConfig>();

  /* Number of modals that are currently opened. */
  public activeModals: Number = 0;

  /**
   * Construct TrxadeModalService object
   */
  constructor() { 
    //This pipe observable is activated when a component send this service a
    //modal config object and receives it.
    this.modalPipe.subscribe((modal) => {
        this.modalComponents.push(modal);
        this.showModal();
    });
  }

  /**
   * Picks a modal config from the available configs and processes it. If there
   * are no current modals being shown and if there are any modals left in the modal pipe,
   * a modal from pipe is picked, processed and displayed.
   */
  showModal() {
    if (this.modalComponents.length > 0 && this.activeModals === 0) {
      this.currentModal = this.modalComponents.shift();
      //If the conditions required to show a pop up are met, showModal will be true.
      if (this.currentModal?.showModal) {
        this.activeModals = 1;
        this.currentModal?.component.openModal();
        this.currentModal?.component.setData(this.currentModal.data);
      }
      //If a currently opened popup is closed this observable gets activated. If there are no
      //currently opened pop ups, a new pop up is opened.
      this.currentModal?.component.modalService.activeInstances.subscribe((activeInstances) => {
        this.activeModals = activeInstances.length;
        if (this.activeModals === 0) {
          this.showModal();
        }
      });
    }
  }
}
