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

import { useDispatch, useSelector } 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 { getHttpHeaderForServiceRequest } from "../actions/commonActions";
import { lunaTest } from "../lunaSend/lunaTest";
import { getLaunchParams, clearLaunchParams } 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 { httpHeader } = useSelector((state) => state.common);

  // called by [receive httpHeader, launch, relaunch]
  const initService = useCallback(
    (haveyInit = true) => {
      console.log(
        "<<<<<<<<<<<<<        appinfo      >>>>>>>>>>>>{heavyInit,  appinfo} ",
        haveyInit,
        appinfo
      );
      if(httpHeader){
        if (haveyInit) {
          dispatch(changeAppStatus({ connectionFailed: false }));
          if (typeof window === "object" && window.PalmSystem) {
            dispatch(
              changeAppStatus({
                cursorVisible: window.PalmSystem?.cursor?.visibility,
              })
            );
          }
          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());
        }
        //todo deeplink
        const launchParams = getLaunchParams();
        console.log(
          "initService...{haveyInit, launchParams}",
          haveyInit,
          launchParams
        );

        if (launchParams?.contentTarget) {
          //todo deeplink
          dispatch(handleDeepLink(launchParams.contentTarget));
        }
        clearLaunchParams();
        dispatch(changeAppStatus({ showLoadingPanel: { show: false } }));
      }
    },
    [dispatch, httpHeader]
  );

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

  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);
    }
  }, [dispatch, initService]);

  useEffect(() => {
    if (typeof window === "object" && window.PalmSystem) {
      window.PalmSystem.activate();
      window.lunaTest = (service, method, subscribe, parameters) =>
        lunaTest(service, method, subscribe, parameters);
    }
    dispatch(getHttpHeaderForServiceRequest());
        //todo subscribe
    // dispatch(getSystemSettings());
    // //get captionEnable
    // dispatch(getSystemSettings2());
    // dispatch(getSystemInfo());
    // dispatch(getDeviceId());
    document.addEventListener("visibilitychange", visibilityChanged);
    document.addEventListener("webOSRelaunch", handleRelaunchEvent);
    return () => {
      document.removeEventListener("visibilitychange", visibilityChanged);
      document.removeEventListener("webOSRelaunch", handleRelaunchEvent);
    };
  }, []);

  useEffect(() => {
    console.log('httpHeader changed ', httpHeader);
    if(!httpHeader){

    }else{ //계정정보 변경시 또는 초기 로딩시
      dispatch(changeAppStatus({ showLoadingPanel: { show: true } }));
      initService(true);
    }
  }, [httpHeader]);

  return <MainView />;
}

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

export default App;
export { App, AppBase };
