import * as React from 'react';
import {
  useContext,
  createContext,
  FunctionComponent,
  useEffect,
  useState,
} from 'react';
import { EditorViewContext } from './EditorViewContext';
import { FontInfo } from '../vs/editor/common/config/fontInfo';
import { EditorOption } from '../vs/editor/common/config/editorOptions';

const initialState = {
  fontInfo: undefined as unknown as FontInfo,
};

export const FontInfoContext = createContext(initialState);

type Props = {
  // nothing
};

export const FontInfoProvider: FunctionComponent<Props> = (props) => {
  const { children } = props;

  const { editor } = useContext(EditorViewContext);

  const [fontInfo, setFontInfo] = useState(
    editor.getOption(EditorOption.fontInfo)
  );

  useEffect(() => {
    editor.onDidChangeConfiguration((evt) => {
      if (evt.hasChanged(EditorOption.fontInfo)) {
        setFontInfo(editor.getOption(EditorOption.fontInfo));
      }
    });
  }, [editor]);

  const value = {
    fontInfo,
  };

  return (
    <FontInfoContext.Provider value={value}>
      {children}
    </FontInfoContext.Provider>
  );
};
