import React, { useState, useEffect } from 'react';
import { LMConfig, Dict } from '@zenview/micro-basic-library';
import { formatAppConfig, querySystemConfig, queryThemeConfig, queryMapConfig, queryMicroApplicationList, queryLogoConfig, queryZenMapConfig, queryZenMap3DConfig } from './utils';
import './index.less';

function InitialConfig({ children, mode = 'server' }) {
  const [state, setState] = useState({ isInit: false, isUpdate: false });
  Dict.useTypeCodes();
  useEffect(() => {
    Promise.all([
      querySystemConfig(mode),
      queryMapConfig(mode),
      queryThemeConfig(mode),
      queryMicroApplicationList(mode),
      queryLogoConfig(),
      queryZenMapConfig(),
      queryZenMap3DConfig(),
    ]).then((res) => {
      const [BSConfig, LMapConfig, themeConfig, AppConfig, LogConfig, ZenMapConfig, ZenMap3DConfig] = res;
      LMConfig.registerBSConfig(BSConfig);
      LMConfig.registerLMapConfig(LMapConfig);
      LMConfig.registerAppConfig(formatAppConfig(AppConfig));
      LMConfig.registerThemeConfig(themeConfig);
      LMConfig.registerLogConfig(LogConfig);
      LMConfig.registerCustomConfig({ ZenMap: ZenMapConfig, ZenMap3D: ZenMap3DConfig });
      setState(() => ({ isUpdate: BSConfig.isUpdate, isInit: true }));
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const { isInit, isUpdate } = state;
  if (!isInit) {
    return null;
  }

  return <>{children(isUpdate)}</>;
}

export default InitialConfig;
