import React, {useCallback, useEffect, useState} from 'react';
import {buildSchema} from 'graphql';
import './App.css';

export const App = ({ context }) => {
  const [ appState, setAppState ] = useState({});
  const [ currentWindowId, setCurrentWindowId ] = useState(null);
  const setQuery = useCallback(({ windowId, data }) => {
    setAppState((appState) => ({
      ...appState,
      [windowId]: {
        ...appState[windowId],
        query: data,
      }
    }));
  }, []);
  const setSDL = useCallback(({ windowId, data }) => {
    setAppState((appState) => ({
      ...appState,
      [windowId]: {
        ...appState[windowId],
        sdl: data,
      }
    }));
  }, []);

  const initializeCurrentWindowState = (state) => {
    setCurrentWindowId(state.windowId);
    let schema = null;
    if (state.sdl) {
      try {
        schema = buildSchema(state.sdl);
      } catch(error) {}
    }

    setAppState((appState) => ({
      ...appState,
      [state.windowId]: {
        ...state,
        schema,
      },
    }));
  };

  useEffect(() => {
    context.app.getCurrentWindowState().then(state => {
      initializeCurrentWindowState(state);
    });
    console.log(appState);

    context.events.on('query.change', setQuery);

    context.events.on('sdl.change', setSDL);

    context.events.on('current-window.change', async({ windowId }) => {
      const newWindowState = await context.app.getWindowState(windowId);
      initializeCurrentWindowState(newWindowState);
    });


    return () => {
      context.events.off();
    };
  }, [ setQuery, setSDL ]);

  if (!appState[currentWindowId]) {
    return null;
  }

  return (
      <div className='nette-panel'>
        <h2>
          Nette debugger
        </h2>
        <p>
          To open the current query in Nette backend and make us of our better error handling, click the button below.
        </p>
        <a href={`${appState[currentWindowId].apiUrl}?query=${appState[currentWindowId].query}&variables=${appState[currentWindowId].variables}`}>Open in Nette</a>
      </div>
  );
};

export default App;