// 使用本地组件库

import pt from 'path';
import { formatDependiencesMap, injectExternals } from '../../utils/adapter/dependencies';

// 使用本地 mock
async function mockUMDload(url) {
  // console.info(url);
  const mockBasePath = pt.join(__dirname, '..', 'mocks', pt.basename(url));
  const exports = (await import(mockBasePath)).default;
  return exports;
}

export async function loadDependiences(dependencies) {
  injectExternals();
  return await Promise.all(
    dependencies.map((item) =>
      Promise.all([
        item.isComposite
          ? Promise.resolve(null)
          : mockUMDload(item.controlJsPath || item.mainJsPath.replace(/\.main\.js/, '.control.js')),
        mockUMDload(item.mainJsPath).then((x) => ({
          ...x,
          name: item.name,
          isComposite: item.isComposite,
        })),
      ]),
    ),
  ).then((results: any[]) => {
    const controls = [],
      components = [];
    results.forEach((raw) => {
      const [control, component] = raw;
      if (control) {
        controls.push(control);
      }
      components.push(component);
    });
    return formatDependiencesMap(components, controls);
  });
}
