import React, { useCallback, useEffect } from "react";

import { useDispatch } from "react-redux";

import platform from "@enact/core/platform";
import ThemeDecorator from "@enact/sandstone/ThemeDecorator";

import appinfo from "../../webos-meta/appinfo.json";
import { changeAppStatus } from "../actions/commonActions";
import { getAuthenticationCode } from "../actions/deviceActions";
import {
  getHomeLayout,
  getHomeMainContents,
  getHomeMenu,
  getThemeCurationInfo,
} from "../actions/homeActions";
import { getSubCategory, getTop20Show } from "../actions/mainActions";
import { getMyRecommandedKeyword } from "../actions/myPageActions";
import { getOnSaleInfo } from "../actions/onSaleActions";
import { getBestSeller } from "../actions/productActions";
import { lunaTest } from "../lunaSend/lunaTest";
import { getLaunchParams } from "../utils/helperMethods";
import MainView from "../views/MainView/MainView";
import css from "./App.module.less";
import { handleDeepLink } from "./deepLinkHandler";

let foreGroundChangeTimer = null;

function AppBase(props) {
  const dispatch = useDispatch();

  const initService = useCallback(
    (haveyInit = true) => {
      console.log(
        "<<<<<<<<<<<<<        appinfo      >>>>>>>>>>>>{heavyInit,  appinfo} ",
        haveyInit,
        appinfo
      );
      if (haveyInit) {
        dispatch(changeAppStatus({ connectionFailed: false }));
        if (typeof window === "object" && window.PalmSystem) {
          dispatch(
            changeAppStatus({
              cursorVisible: window.PalmSystem?.cursor?.visibility,
            })
          );
        }
        //todo
        // dispatch(getSystemSettings());
        // //get captionEnable
        // dispatch(getSystemSettings2());
        // dispatch(getSystemInfo());
        // dispatch(getDeviceId());
        // dispatch(getHttpHeaderForServiceRequest(webOSVersion, language));

        dispatch(getAuthenticationCode());
        dispatch(getOnSaleInfo({ categoryIncFlag: "Y", lgCatCd: "" }));
        dispatch(getHomeMenu());
        dispatch(getHomeLayout());
        dispatch(getHomeMainContents());
        dispatch(getMyRecommandedKeyword());
        dispatch(getBestSeller());
        dispatch(
          getSubCategory({
            lgCatCd: "1017", //LG Electronics Base
            patnrIdList: null,
            pageSize: null,
            tabType: null,
            filterType: null,
          })
        );
        dispatch(getTop20Show());
        dispatch(getThemeCurationInfo());
      }
    },
    [dispatch]
  );

  const handleLaunchEvent = useCallback(
    (isRelaunch = false) => {
      //todo deeplink
      const launchParams = getLaunchParams();
      console.log(
        "handleLaunchEvent...{isRelaunch, launchParams}",
        isRelaunch,
        launchParams
      );

      if (launchParams?.contentTarget) {
        //todo deeplink
        dispatch(handleDeepLink(launchParams.contentTarget));
      }

      setTimeout(() => {
        initService(!isRelaunch);
      }, 100);
    },
    [initService]
  );

  const handleRelaunchEvent = useCallback(() => {
    console.log("handleRelaunchEvent started");
    handleLaunchEvent(true);
  }, [handleLaunchEvent]);

  const visibilityChanged = useCallback(() => {
    console.log("document is hidden", document.hidden);
    console.log("document.visibilityState= ", document.visibilityState);
    if (document.hidden && typeof window === "object") {
      clearTimeout(foreGroundChangeTimer);
    } else {
      // change to foreground
      // set foreground flag using delay time.
      clearTimeout(foreGroundChangeTimer);
      foreGroundChangeTimer = setTimeout(() => {
        console.log(
          "visibility changed !!! ==> set to foreground cursorVisible",
          JSON.stringify(window.PalmSystem?.cursor?.visibility)
        ); // eslint-disable-line no-console
        if (platform.platformName !== "webos") {
          //for debug
          dispatch(
            changeAppStatus({
              isAppForeground: true,
              cursorVisible: !platform.touchscreen,
            })
          );
        } else if (typeof window === "object") {
          dispatch(
            changeAppStatus({
              isAppForeground: true,
              cursorVisible: window.PalmSystem?.cursor?.visibility,
            })
          );
        }
      }, 1000);
      setTimeout(() => {
        initService(false);
      }, 100);
    }
  }, [dispatch, initService]);

  useEffect(() => {
    if (typeof window === "object" && window.PalmSystem) {
      window.PalmSystem.activate();
      window.lunaTest = (service, method, subscribe, parameters) =>
        lunaTest(service, method, subscribe, parameters);
    }
    handleLaunchEvent();
    document.addEventListener("visibilitychange", visibilityChanged);
    document.addEventListener("webOSRelaunch", handleRelaunchEvent);
    return () => {
      document.removeEventListener("visibilitychange", visibilityChanged);
      document.removeEventListener("webOSRelaunch", handleRelaunchEvent);
    };
  }, [dispatch]);

  return <MainView />;
}

const App = ThemeDecorator({ noAutoFocus: true }, AppBase);

export default App;
export { App, AppBase };
