import { useRef, useEffect } from "react";
import { useSelector as useReduxSelector } from "react-redux";
import { useState as useReactState } from "react";

/**
 *
 * @param {*} name log name
 * @param {*} props props object
 *  const {USE_STATE, USE_SELECTOR}= useWhyDidYouUpdate("testPanel", {spotlightId, panelInfo});
 * @returns
 */
const useWhyDidYouUpdate = (name, props) => {
  return {
    USE_STATE: (stateName, initialValue) => useReactState(initialValue),
    USE_SELECTOR: (selectorName, selector, equalityFn) => useReduxSelector(selector, equalityFn),
  };

  /*
  // 디버깅 하려면 윗부분 주석처리하고 아래부분 살리면 됨.
  // Effect는 조건 처리가 안되서 부득이하게..
  const previousProps = useRef(props);
  useEffect(() => {
    console.log("[why-did-you-update] created ", name, props);
  }, []);

  useEffect(() => {
    if (previousProps.current) {
      const allKeys = Object.keys({ ...previousProps.current, ...props });
      const changesObj = {};
      allKeys.forEach((key) => {
        if (previousProps.current[key] !== props[key]) {
          changesObj[key] = {
            from: previousProps.current[key],
            to: props[key],
          };
        }
      });

      if (Object.keys(changesObj).length) {
        console.log("[why-did-you-update]", name, changesObj);
      }
      previousProps.current = props;
    }
  }, [props, name]);

  //const [count, setCount] = USE_STATE('count', 0);
  const USE_STATE = (stateName, initialValue) => {
    const [state, setState] = useReactState(initialValue);
    const previousState = useRef(state);

    useEffect(() => {
      if (previousState.current !== state) {
        console.log("[why-did-you-update]", `${name}.${stateName}`, {
          from: previousState.current,
          to: state,
        });
        previousState.current = state;
      }
    }, [state]);
    return [state, setState];
  };

  // const user = USE_SELECTOR('user', state => state.user, equalityFn);
  const USE_SELECTOR = (selectorName, selector, equalityFn) => {
    const selectedState = useReduxSelector(selector, equalityFn);
    const previousState = useRef(selectedState);

    useEffect(() => {
      if (previousState.current !== selectedState) {
        console.log("[why-did-you-update]", `${name}.${selectorName}`, {
          from: previousState.current,
          to: selectedState,
        });
        previousState.current = selectedState;
      }
    }, [selectedState]);
    return selectedState;
  };
  return { USE_STATE, USE_SELECTOR };
  */
};

export default useWhyDidYouUpdate;
