import { useCallback, useEffect, useRef, useMemo } from "react";

import { useDispatch, useSelector } from "react-redux";

import { off, on } from "@enact/core/dispatcher";

import { pushPanel } from "../actions/panelActions";
import * as Config from "../utils/Config";

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

  const isPrdServer = useMemo(() => {
    if(typeof window === "object" && !window.PalmSystem ){
      return false;
    }

    if (!serverHOST) return true;

    if (serverType === "system") {
      const sdpURL = serverHOST.toLowerCase();
      if (sdpURL.indexOf("qt2") >= 0 || sdpURL.indexOf("qt") >= 0) {
        return false;
      }
    } else {
      return false;
    }
    return true;
  }, [serverType, serverHOST]);

  const handleKeydown = useCallback(
    (ev) => {
      if (isPrdServer) return;

      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: {} }));
        }
        if (debugKey.current.join("") === Config.TESTPANEL_KEY) {
          debugKey.current = [];
          dispatch(
            pushPanel({
              name: Config.panel_names.VIDEO_TEST_PANEL,
              panelInfo: {},
            })
          );
        }
      }
    },
    [panels, dispatch, isLandingPage, isPrdServer]
  );

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

export default useDebugKey;
