import { observable } from 'mobx'
import { createMpApp } from '@cloudbase/weda-client';
import { createComputed, formatEnum, enumOptions } from '<%= subLevelPath %>../common/util'
import process from '<%= subLevelPath %>../common/process'
import appGlobal from '<%= subLevelPath %>../app/app-global'
import { createDataset } from '<%= subLevelPath %>../datasources/index'

<%= importor.state? `import state from '../lowcode/state'` : "const state = {}" %>
<%= importor.computed? `import computed from '../lowcode/computed'` : "const computed = {}" %>
<%= importor.common? `import common from './common'` : "const common = {}" %>

const mainAppKey = '__weappsMainApp'

export const app = createGlboalApi()
export { process }

function createGlboalApi() {
  const mpApp = createMpApp({
    appConfig: <%= appConfig %>
  });
  const globalAPI = {
    id: '<%= appId %>',
    domain: '<%= domain %>',
    pages: {},
    session: {
      //configure: sdk.configure,
      //request: sdk.request,
      //getSessionId: sdk.getSessionId,
    },
    state: observable(state),
    computed: createComputed(computed),
    common,
    ...mpApp,
    invoke(params) {
      const $page = globalAPI.utils.getCurrentPage();
      return $page.invokeComponentMethod(params)
    },
    // ... other sdk apis & apis from mp
  } // The global api exposed to lowcode

  globalAPI.__internal__.enumOptions = enumOptions
  globalAPI.utils.formatEnum = formatEnum
  /**
   * @deprecated utils._getConfig
   */
  globalAPI.utils._getConfig = () => {
    return globalAPI.__internal__.getConfig()
  }

  let dataset = createDataset('$global')
  globalAPI.dataset = dataset
  globalAPI.state.dataset = dataset
  globalAPI.setState = (userSetState) => {
    Object.keys(userSetState).forEach((keyPath) => {
      globalAPI.utils.set(globalAPI.dataset.state, keyPath, userSetState[keyPath]);
    });
  };

  const subPackageName = '<%= subPackageName %>'
  if (subPackageName) {
    // is sub app
    globalAPI.mainApp = appGlobal[mainAppKey]
    const mpApp = getApp()
    mpApp && (mpApp.subApp = globalAPI)
  } else {
    // is mainApp
    appGlobal[mainAppKey] = globalAPI
  }

  // # expose some sdk modules
  /* const sdkModsIncluded = ['flow', 'getPageOptions', 'getLaunchOptions']
  sdkModsIncluded.forEach(key => {
    globalAPI[key] = sdk[key]
  }) */

  return globalAPI
}
