import { useState, useEffect } from 'react';

/**
 * Utility hook to throw an async error when a Canvas element switches between
 * controlled and uncontrolled during its lifecycle. Really just here to keep
 * this error reporting logic out of the main `useZoom` hook.
 *
 * @param {boolean} isControlled
 */
const useControlSwitchError = function useControlSwitchError(isControlled) {
  // Keep track of initial state of control
  const [wasControlledFromStart] = useState(isControlled);
  useEffect(() => {
    const throwAsyncError = async error => {
      throw error;
    };

    // went from uncontrolled to controlled
    if (isControlled && !wasControlledFromStart) {
      throwAsyncError(new Error('Warning: A component is changing an uncontrolled zoom Canvas to be ' + 'controlled. This is likely caused by the value of the `zoom` prop ' + 'changing from undefined to a defined value, which should not ' + 'happen. Decide between using a controlled or uncontrolled zoom ' + 'Canvas for the lifetime of the component.'));
    }

    // went from controlled to uncontrolled
    if (!isControlled && wasControlledFromStart) {
      throwAsyncError(new Error('Warning: A component is changing a controlled zoom Canvas to be ' + 'uncontrolled. This is likely caused by the value of the `zoom` ' + 'prop changing from a defined value to undefined, which should ' + 'not happen. Decide between using a controlled or uncontrolled ' + 'zoom Canvas for the lifetime of the component.'));
    }
  }, [isControlled]);
};
export default useControlSwitchError;