import { LowCodeModuleParser, IEvaledModule, LowcodeContext } from './base';

function getDefaultModule(targetModule) {
  if (!targetModule) {
    return targetModule;
  }
  const keys = Object.keys(targetModule);
  if (keys.length === 1 && keys[0] === 'default') {
    return targetModule.default;
  }
  return targetModule;
}

export class NormalModuleParser implements LowCodeModuleParser {
  common: any;

  onStart(context: LowcodeContext) {
    this.common = {};
  }

  parseModule(pageId: string, mod: IEvaledModule) {
    if (mod.name === '____index____') return;

    const [, , folder] = mod.path?.split('/');
    if (folder) {
      this.common[pageId] = this.common[pageId] || {};
      this.common[pageId][folder] = getDefaultModule(mod.exports);
    } else {
      this.common[pageId] = getDefaultModule(mod.exports);
    }
  }

  onEnd(context: LowcodeContext) {
    context.common = this.common;
  }
}
