import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class ModalService {
  private _modalSubject = new Subject<any>();
  modal$ = this._modalSubject.asObservable();

  private _closeModalSubject = new Subject<any>();
  closeModal$ = this._closeModalSubject.asObservable();

  private _resultSubject = new Subject<any>();
  result$ = this._resultSubject.asObservable();

  private _actionSubject = new Subject<any>();
  action$ = this._actionSubject.asObservable();

  private _isModalOpen = false;
  public get isModalOpen(): boolean {
    return this._isModalOpen;
  }

  /**
   * Opens the modal with the specified component and provides the data as input for the component.
   * @param component The component to open in the modal.
   * @param data The data for the input of the component.
   */
  public openModal(component: any, data: any) {
    this._isModalOpen = true;
    this._modalSubject.next({ component, data });
  }

  /**
   * This function closes the modal and sends a result state and an optinal data object to the host component.
   * @param result The result state. Can be 'cancel', 'update' etc.
   * @param data The oprional data object that eg contains a new or modifed weapon object.
   */
  public handleModalClosing(result: any, data?: any) {
    //The host components subscribes to the result$ Observable to get the result of the modal
    this._resultSubject.next({ state: result, data: data });
    this._closeModalSubject.next('close');
    this._isModalOpen = false;
  }

  /**
   * Sends a message to the host component that openend the modal.
   * @param action The action to perform.
   * @param data The optional data to send.
   */
  public sendMessage(action: string, data?: any) {
    this._actionSubject.next({ action, data });
  }
}
