import React, {useReducer, useEffect} from 'react';
import MainLayout from './MainLayout';
import {fsReducer, initialState, StoreContext, StoreDispatchContext, narrowAppDataPayload} from './store';
import './App.css';

function App() {
  const [store, storeDispatch] = useReducer(fsReducer, initialState);

  useEffect(() => {
    window.parent.postMessage({type: "requestAppData"}, "*");
    storeDispatch({type: 'APPDATA_SET_LOADING'});
    function listener(ev: WindowEventMap["message"]) {
      // typecheck the payload
      if (ev.data.type === "appData") {
        if (narrowAppDataPayload(ev.data.payload)) {
          storeDispatch({
            type: 'APPDATA_SET_LOADED',
            payload: {
              manifest: ev.data.payload.manifest,
              appIntegrations: ev.data.payload.appIntegrations,
              apptileConfig: ev.data.payload.apptileConfig,
              bundles: ev.data.payload.bundles
            }
          });
        } else {
          const errorMessage = "Invalid appData received from host " + JSON.stringify(ev.data.payload);
          storeDispatch({
            type: 'APPDATA_SET_ERROR',
            payload: {
              err: new Error(errorMessage),
              message: errorMessage
            }
          });
        }
      } else {
        console.warn("Ignoring event: ", ev);
      }
    }
    window.addEventListener("message", listener);
    return () => {
      window.removeEventListener("message", listener)
    };
  }, [storeDispatch]); 

  return (
    <StoreContext.Provider value={store}>
      <StoreDispatchContext.Provider value={storeDispatch}>
        <MainLayout />
      </StoreDispatchContext.Provider>
    </StoreContext.Provider>
  );
}

export default App;
