import { action, computed, makeObservable } from 'mobx';
import { AppBase } from '../app/AppBase';
import { getUniqueId } from '../utils/string/getUniqueId';
import { FeedbackType } from '../models/Feedback';

/**
 * Default store for Apphouse
 * Your store must extend this class
 */
export class ApphouseStore {
  /**
   * A random uuid for the app
   * This number is used to ensure that the appStore is unique
   * and you are accessing the correct store
   */
  uuid: string;
  /**
   * The base app
   */
  app: AppBase;

  constructor(appName: string) {
    this.uuid = `apphouse-${appName}-${getUniqueId()}`;
    makeObservable(this, {
      theme: computed,
      path: computed,
      open: action,
      openPopup: action,
      routes: computed,
      alert: action,
      closePopup: action
    });

    this.app = new AppBase({ appName });
  }

  get path() {
    return this.app.view.path;
  }

  get theme() {
    return this.app.settings.theme.theme;
  }

  get routes() {
    return this.app.view.routes;
  }

  open = (path: string, title?: string, onOpen?: () => void) => {
    this.app.view.open(path, title, onOpen);
  };

  openPopup = (popup: JSX.Element) => {
    this.app.popups.set(
      popup.props.id,
      popup.props.title,
      popup.props.data,
      popup
    );
  };

  alert = (settings: FeedbackType) => {
    this.app.feedback.setFeedback(settings);
  };

  /**
   * Call this method to close a popup in the app
   * @param popupId the popup you want to close, if not provided, the last opened popup will be closed
   */
  closePopup = (popupId?: string) => {
    const popups = this.app.popups;
    if (popupId) {
      popups.remove(popupId);
    } else {
      popups.pop();
    }
  };
}
