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

export class StateParser implements LowCodeModuleParser {
  state: { [pageId: string]: any };

  onStart() {
    this.state = {};
  }

  parseModule(pageId: string, mod: IEvaledModule) {
    const stateObj = mod.exports?.default || mod.exports;
    if (typeof stateObj === 'object') {
      // FIXME
      const plain = JSON.parse(JSON.stringify(stateObj)); // Creating observable from object defined in another context(lowcode state is executed in the iframe) will fail
      this.state[pageId] = plain;
    } else if (typeof stateObj === 'function') {
      const plain = JSON.parse(JSON.stringify(stateObj.call())); // Creating observable from object defined in another context(lowcode state is executed in the iframe) will fail
      this.state[pageId] = plain;
    } else {
      throw new Error('state must export an object or function');
    }
  }

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