import * as React from 'react';
import {
  createContext,
  FunctionComponent,
  useEffect,
  useCallback,
} from 'react';
import { MouseDownState } from '../utilities';
import { useConst } from '../hooks';

const initialState = {
  mouseDownState: new MouseDownState(),
};

export const MouseMonitorContext = createContext(initialState);

type Props = {};

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

  const mouseDownState = useConst(() => {
    console.log(`Create MouseDonwState`);
    return new MouseDownState();
  });

  const onMouseDown = useCallback(
    (evt: MouseEvent) => {
      const { clientX, clientY, button } = evt;
      mouseDownState.setStartButtons({ leftButton: button === 0 });
      mouseDownState.setPosition({ x: clientX, y: clientY });
    },
    [mouseDownState]
  );

  useEffect(() => {
    // window.addEventListener('mousedown', (evt) => {
    //   const { clientX, clientY, button } = evt;
    //   mouseDownState.setStartButtons({ leftButton: button === 0 });
    //   mouseDownState.setPosition({ x: clientX, y: clientY });
    // });
    window.addEventListener('mousedown', onMouseDown);

    window.addEventListener('mousemove', (evt) => {
      const { clientX, clientY } = evt;
      // mouseDownState.setStartButtons({ leftButton: evt.button === 0 });
      mouseDownState.setPosition({ x: clientX, y: clientY });
    });

    window.addEventListener('mouseup', (evt) => {
      mouseDownState.setStartButtons({ leftButton: !(evt.button === 0) });
    });
    return () => {
      window.removeEventListener('mousedown', onMouseDown);
    };
  }, [mouseDownState, onMouseDown]);

  const value = {
    mouseDownState,
  };

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