import React from "react";
import { Provider } from "redux-bundler-react";
import Corpsmap from "../application-containers/corpsmap";
import getStore from "../application-bundles";
import cache from "../utils/cache";
import loadPlugins from "../utils/load-plugins";
import config from "../config/default-config.js";
import pkg from "../../package.json";

import "ol/ol.css";
import "../css/mdi/css/materialdesignicons.min.css";
import "../css/mapskin/css/mapskin.min.css";
import "../css/navigation.css";
import "../css/cm-icons/css/cm-icons.css";
import "../css/loading-indicator.css";
import "../css/corpsmap-namespaced.css";

console.log("------ RUNNING CORPSMAP V." + pkg.version + " ------");

class Map extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      store: null,
    };
    this.getStore = this.getStore.bind(this);
  }

  getStore() {
    return this.state.store;
  }

  componentDidMount() {
    const {
      mapConfig = {},
      plugins = [],
      height,
      theme,
      themeNavSize,
      basemaps,
      limitMapExtent,
    } = this.props;

    cache.getAll().then((initialData) => {
      initialData.config = {
        default: Object.assign({}, config, mapConfig),
      };
      
      if (basemaps) {
        basemaps.forEach((basemap) => {
          initialData.config.default.basemaps.push(basemap);
        });
      }

      if (height) {
        initialData.vLayout = {
          height: height,
          hNorth: 1,
          hSouth: 0,
        };
      }

      if (theme) {
        const themeName = theme.indexOf("bg-") === -1 ? `bg-${theme}` : theme;
        initialData.theme = {
          theme: themeName,
          iconSize: themeNavSize || "default",
        };
      }

      if (limitMapExtent) {
        initialData.config.default.limitMapExtent = limitMapExtent;
      }
      
      const store = getStore(initialData);
      loadPlugins(store, plugins);

      window.internalStore = store;

      this.setState({
        store: store,
      });
    });
  }

  render() {
    const { store } = this.state;
    if (!store) return null;
    return (
      <Provider store={store}>
        <Corpsmap {...this.props} />
      </Provider>
    );
  }
}

export default Map;
