import React from "react";
import * as TaroComponents from "@tarojs/components";
import * as ComUtils from "@fangzhou/com-utils";

const packages = {
  react: React,
  "@fangzhou/ktaro-components": TaroComponents,
  "@fangzhou/com-utils": ComUtils,
};

const getParsedModule = (filename: string, code: string) => {
  try {
    let module = {
      exports: {},
    };
    const require = (name: string) => {
      return packages[name];
    };
    new Function("require, exports, module", code)(require, module.exports, module);
    return module;
  } catch (e) {
    console.log(`${filename}执行出错`, e);
  }
};

const fetchComponent = async (name: string, runtime: string) => {
  console.log("name", name);
  try {
    let text = runtime;
    if (runtime?.match(/^http/)) {
      text = await fetch(runtime).then((result) => {
        return result.text();
      });
    } else {
      console.log(text);
    }

    const module = getParsedModule(name, text);
    if (!module) return Promise.reject(new Error("No Module"));
    if (module && typeof module.exports === "object") {
      return Promise.resolve((module.exports as any)?.default);
    }
    return Promise.resolve(module.exports);
  } catch (e) {
    return Promise.reject(e);
  }
};

export default fetchComponent;
