import * as React from 'react';
import {
  useContext,
  createContext,
  FunctionComponent,
  useEffect,
  useState,
} from 'react';
import { EditorViewContext } from './EditorViewContext';
import { Position } from '../vs/editor/common/core/position';

const initialState = {
  cursorPosition: undefined as Position | undefined,
};

export const CursorPositionContext = createContext(initialState);

type Props = {
  // nothing
};

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

  const { editor, renderingContext: ctx } = useContext(EditorViewContext);

  const [cursorPosition, setCursorPosition] = useState<Position | undefined>();

  useEffect(() => {
    editor.onDidChangeCursorPosition((evt) => {
      if (!ctx) {
        return;
      }
      const { position } = evt;

      const viewPositon = ctx.viewportData.convertModelPositionToViewPosition(
        position.lineNumber,
        position.column
      );

      setCursorPosition(viewPositon);
    });
  }, [editor, ctx]);

  const value = {
    cursorPosition,
  };

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