import { useRef, useCallback, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import * as Config from "../utils/Config";
import { on, off } from "@enact/core/dispatcher";
import { pushPanel } from "../actions/panelActions";

const useDebugKey = ({isLandingPage=false}) => {
  const panels = useSelector((state) => state.panels.panels);
  const debugKey = useRef([]);
  const dispatch = useDispatch();

  const handleKeydown = useCallback(
    (ev) => {
      if (isLandingPage && panels && panels.length > 0) {
        return;
      }
      if (ev && ev.key >= 0 && ev.key <= 9) {
        if (debugKey.current.length >= Config.DEBUG_KEY.length) {
          debugKey.current.shift();
        }
        debugKey.current.push(String(ev.key));
        if (debugKey.current.join("") === Config.DEBUG_KEY) {
          debugKey.current = [];
          dispatch(pushPanel({ name: Config.panel_names.DEBUG_PANEL, panelInfo: {} }));
        }
      }
    },
    [panels, dispatch, isLandingPage]
  );

  useEffect(() => {
    on("keydown", handleKeydown);
    return () => {
      off("keydown", handleKeydown);
    };
  }, [handleKeydown]);

};

export default useDebugKey;