import {
  WixPatternsContainer,
  HostContainerExtension,
  TaskState,
} from '@wix/bex-core';
import { computed, makeObservable } from 'mobx';

export interface ExtensionsStateParams {
  containerId?: string;
  containerProps?: Record<string, any>;
  container: WixPatternsContainer;
}

export class ExtensionsState {
  readonly _container: WixPatternsContainer;
  readonly _containerId?: string;
  readonly _containerProps?: Record<string, any>;

  readonly initTask = new TaskState<HostContainerExtension[]>();

  constructor(params: ExtensionsStateParams) {
    this._container = params.container;
    this._containerId = params.containerId;
    this._containerProps = params.containerProps;

    makeObservable(this, {
      items: computed,
    });
  }

  get items() {
    return this.initTask.status.data || [];
  }

  init() {
    const { initTask } = this;

    initTask.runOnce(async () => {
      const {
        _container: { getHostContainer },
        _containerId,
      } = this;

      if (!getHostContainer || !_containerId) {
        return [];
      }

      const hostContainer = getHostContainer(_containerId);
      const items = await hostContainer.getExtensions(); // it's not really async, here for backwards compatibility with old biz types and eventually can be replaced with getContainerMenuItems

      return items;
    });
  }
}
