import { startStimulusApp } from '@symfony/stimulus-bridge';
import { Controller as StimulusController } from '@hotwired/stimulus';

// Registers Stimulus controllers from controllers.json and in the controllers/ directory
export const app = startStimulusApp(require.context(
    '@symfony/stimulus-bridge/lazy-controller-loader!./controllers',
    true,
    /\.[jt]sx?$/
));

if (process.env.NODE_ENV === "development") {
   app.debug = true;
}

export const components = new Map();

export function _isStimulusController(component) {
   return component instanceof Function && component.prototype instanceof StimulusController;
}

export function loadComponent(name, component, selector) {
   if (_isStimulusController(component.default)) {
      components.set(name, component.default);
      app.register(name, component.default);
   } else if (component.default instanceof Function) {
      components.set(name, new component.default(selector));
   } else {
      components.set(name, null);
   }
}

export async function lazyLoadComponent(root, name, selector, jsLoader, cssLoader) {
   if (!components.get(name) && root.querySelector(selector)) {
      if (jsLoader) {
         const component = await jsLoader();
         loadComponent(name, component, selector);
      }
      if (cssLoader) {
         await cssLoader();
      }
   }
}

export function createComponents(root) {
   for (let [name, component] of components) {
      if (!component) {
         continue;
      }

      if (_isStimulusController(component)) {
         continue;
      }

      if (component.create && root.querySelector(component.selector)) {
         component.create(root);
      }
   }
}

