import appinfo from "../../webos-meta/appinfo.json";
import { alertToast } from "../actions/commonActions";
import { store } from "../store/store";
import LS2Request from "./LS2Request";

export const getConnectionStatus = ({ onSuccess, onFailure, onComplete }) => {
  if (typeof window === "object" && !window.PalmSystem) {
    console.log("LUNA SEND getConnectionStatus");

    //test
    // setTimeout(() => {
    //   onSuccess({
    //     returnValue: true,
    //     wifi: { state: "disconnected", onInternet: "no" },
    //     wired: { state: "disconnected", onInternet: "no" },
    //   });

    //   setTimeout(() => {
    //     onSuccess({
    //       returnValue: true,
    //       wifi: { state: "connected", onInternet: "yes" },
    //       wired: { state: "connected", onInternet: "yes" },
    //     });
    //   }, 20000);
    // }, 10000);

    return "Some Hard Coded Mock Data";
  } else {
    return new LS2Request().send({
      service: "luna://com.webos.service.connectionmanager",
      method: "getStatus",
      subscribe: true,
      parameters: {},
      onSuccess,
      onFailure,
      onComplete,
    });
  }
};

export const createToast = (message) => {
  if (typeof window === "object" && !window.PalmSystem) {
    console.log("LUNA SEND createToast message", message);
    return;
  }
  return new LS2Request().send({
    service: "luna://com.webos.notification",
    method: "createToast",
    parameters: {
      message: message,
      iconUrl: "",
      noaction: true,
    },
    onSuccess: (res) => {
      console.log("LUNA SEND createToast success", message);
    },
    onFailure: (err) => {
      console.log("LUNA SEND createToast failed", err);
    },
  });
};

let httpHeaderHandler = null;
export const getHttpHeaderForServiceRequest = ({
  onSuccess,
  onFailure,
  onComplete,
}) => {
  if (
    typeof window === "object" &&
    window.PalmSystem &&
    process.env.REACT_APP_MODE !== "DEBUG"
  ) {
    if (httpHeaderHandler) {
      httpHeaderHandler.cancel();
    }
    httpHeaderHandler = new LS2Request().send({
      service: "luna://com.webos.service.sdx",
      method: "getHttpHeaderForServiceRequest",
      subscribe: true,
      parameters: {},
      onSuccess: (res) => {
        try {
          console.log("[serverHost][LS2] onSuccess HOST:", res && res.HOST);
          console.log("[serverHost][LS2] onSuccess raw:", res);
        } catch (e) {}
        onSuccess && onSuccess(res);
      },
      onFailure: (err) => {
        console.log("[serverHost][LS2] onFailure:", err);
        onFailure && onFailure(err);
      },
      onComplete: (res) => {
        console.log("[serverHost][LS2] onComplete:", res);
        onComplete && onComplete(res);
      },
    });
    return httpHeaderHandler;
  } else {
    const serverType = store.getState().localSettings.serverType;

    const userNumber =
      serverType === "prd" ? "US2412306099093" : "US2210240095608";

    const mockRes = {
      HOST: "qt2-US.nextlgsdp.com",
      "X-User-Number": userNumber,
      Authorization:
        "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJuZXh0bGdzZHAuY29tIiwiYXVkIjoibmV4dGxnc2RwLmNvbSIsImlhdCI6MTcwNzc4NTUyNSwiZXhwIjoxNzA3NzkyNzI1LCJtYWNBZGRyZXNzIjoiZWVkMDQ2NjdiNjUzOWU3YmQxMDA1OTljYjBkYTI5ZjRjZTgyZGZlOGZkNzIzMDAxZGVmMjg4NWRkNWZiODRmNWNiMzZlM2QwNzYzNWZjZGJjYWNjNGVjMzI5NWIwNjZjOTMwNmNmNDI1ZGQzMmQ2MDMxMjc1NWNkOTIyNjEwMzcifQ.vqPdYGnN46diesDBLzA4UhACCJVdIycLs7wZu9M55Hc",
      "X-Authentication": "MkOLvUocrJ69RH/iV1ZABJhjR2g=",
      "X-Device-ID":
        "OemUY5qbPITZv96QKlxrtcqT6ypeX6us2qANLng3/0QCUhv2mecK1UDTMYb/hjpjey9dC/kFycc/5R8u+oK56JIWyYC4V278z64YDPKbDXIsd+eECvyf+Rdm8BneIUPM",
      "X-Device-Product": "webOSTV 6.0",
      "X-Device-Platform": "W21A",
      "X-Device-Model": "HE_DTV_W20P_AFADATAA",
      "X-Device-Eco-Info": "1",
      "X-Device-Country": "US",
      "X-Device-Language": "en-US",
      "X-Device-Netcast-Platform-Version": "6.4.0",
      "X-Device-Publish-Flag": "N",
      "X-Device-Fck": "253",
      "X-Device-SDK-VERSION": "1.0.0",
      "X-Device-Eula":
        "additionalDataAllowed,takeOnAllowed,networkAllowed,generalTermsAllowed,chpAllowed,customAdAllowed,acrOnAllowed,voice2Allowed,voiceAllowed,acrAdAllowed",
    };
    try {
      console.log("[serverHost][LS2][MOCK] onSuccess HOST:", mockRes.HOST);
      console.log("[serverHost][LS2][MOCK] onSuccess raw:", mockRes);
    } catch (e) {}
    onSuccess(mockRes);
  }
};

export const getSystemSettings = (
  parameters,
  { onSuccess, onFailure, onComplete }
) => {
  if (
    typeof window === "object" &&
    window.PalmSystem &&
    process.env.REACT_APP_MODE !== "DEBUG"
  ) {
    return new LS2Request().send({
      service: "luna://com.webos.settingsservice",
      method: "getSystemSettings",
      subscribe: true,
      parameters: parameters,
      onSuccess,
      onFailure,
      onComplete,
    });
  } else if (typeof window === "object") {
    const language =
      typeof window.navigator === "object"
        ? window.navigator.language || window.navigator.userLanguage
        : "en-US";
    const res = {
      settings: {
        smartServiceCountryCode2: language.split("-")[1],
        captionEnable: true,
      },
      returnValue: true,
    };
    onSuccess(res);
    onComplete(res);
  }
};

export function checkValidCountry(ricCode, country) {
  if (ricCode === "aic") {
    if (country === "US") return true;
    else return false;
  } else if (ricCode === "eic") {
    if (country === "GB" || country === "DE") return true;
    else return false;
  } else if (ricCode === "ruc") {
    if (country === "RU") return true;
    else return false;
  } else {
    if (country === "US") {
      return true;
    } else {
      return false;
    }
  }
}

// 3.0 ~ 4.5
export const setSubtitleEnable = (
  mediaId,
  captionEnable,
  { onSuccess, onFailure, onComplete }
) => {
  if (
    typeof window === "object" &&
    window.PalmSystem &&
    process.env.REACT_APP_MODE !== "DEBUG"
  ) {
    if (captionEnable) {
      return new LS2Request().send({
        service: "luna://com.webos.service.tv.subtitle",
        method: "enableSubtitle",
        parameters: { pipelineId: mediaId },
        onSuccess,
        onFailure,
        onComplete,
      });
    } else {
      return new LS2Request().send({
        service: "luna://com.webos.service.tv.subtitle",
        method: "disableSubtitle",
        parameters: { pipelineId: mediaId },
        onSuccess,
        onFailure,
        onComplete,
      });
    }
  }
};

// 5.0
export const setSubtitleEnableOver5 = (
  mediaId,
  captionEnable,
  { onSuccess, onFailure, onComplete }
) => {
  if (typeof window === "object" && window.PalmSystem) {
    return new LS2Request().send({
      service: "luna://com.webos.media",
      method: "setSubtitleEnable",
      parameters: { enable: captionEnable, mediaId: mediaId },
      onSuccess,
      onFailure,
      onComplete,
    });
  }
};

// system Alert with time validation
export const addReservation = (data, { onSuccess, onFailure, onComplete }) => {
  if (typeof window === "object" && !window.PalmSystem) {
    console.log("LUNA SEND addReservation data", data);
    return;
  }

  const createReservation = () => {
    return new LS2Request().send({
      service: "luna://com.webos.service.tvReservationAgent",
      method: "add",
      parameters: {
        scheduleType: "LGShopping",
        startTime: {
          year: data.startTime.year,
          month: data.startTime.month,
          day: data.startTime.day,
          hour: data.startTime.hour,
          minute: data.startTime.minute,
          second: data.startTime.second,
        },
        callback: {
          method: "luna://com.webos.notification/createAlert",
          params: {
            message: data.params.message,
            buttons: [
              {
                label: data.params.buttons[0].label,
                onclick: "luna://com.webos.applicationManager/launch",
                params: {
                  id: window.PalmSystem.identifier ?? appinfo.id,
                  params: data.params.launch,
                },
              },
              {
                label: data.params.buttons[1].label,
              },
            ],
            autoTimeout: 30,
          },
        },
        information: {
          showId: data.params.showId,
          chanId: data.params.chanId,
        },
      },
      onSuccess,
      onFailure: (err) => {
        console.log("LUNA SEND addReservation failed", err);
        // Check if error is related to invalid current time
        if (
          err &&
          err.errorText &&
          err.errorText.includes("Invalid current time")
        ) {
          console.log(
            "Invalid current time error detected, will retry after time validation"
          );
          // Don't call onFailure immediately, let the retry logic handle it
          return;
        }
        onFailure(err);
      },
      onComplete,
    });
  };

  // First, validate system time before creating reservation
  const validateTimeAndCreateReservation = (retryCount = 0, maxRetries = 3) => {
    console.log(`LUNA SEND validating system time, attempt ${retryCount + 1}`);

    getSystemTime({
      onSuccess: (timeRes) => {
        console.log("LUNA SEND system time validation success", timeRes);
        // Time is available, proceed with reservation
        createReservation();
      },
      onFailure: (timeErr) => {
        console.log("LUNA SEND system time validation failed", timeErr);

        if (retryCount < maxRetries) {
          // Retry with exponential backoff
          const delay = Math.min(1000 * Math.pow(2, retryCount), 5000); // Max 5 seconds
          console.log(`LUNA SEND retrying time validation in ${delay}ms`);

          setTimeout(() => {
            validateTimeAndCreateReservation(retryCount + 1, maxRetries);
          }, delay);
        } else {
          console.log("LUNA SEND max retries exceeded for time validation");
          // Still try to create reservation as fallback
          createReservation();
        }
      },
      onComplete: () => {
        console.log("LUNA SEND system time validation complete");
      },
    });
  };

  // Start the validation and reservation process
  validateTimeAndCreateReservation();
};

export const deleteReservationCallback = (
  scheduleIdList,
  { onSuccess, onFailure, onComplete }
) => {
  if (typeof window === "object" && !window.PalmSystem) {
    console.log(
      "LUNA SEND deleteReservationCallback scheduleIdList",
      scheduleIdList
    );
    return;
  }

  return new LS2Request().send({
    service: "luna://com.webos.service.tvReservationAgent",
    method: "delete",
    parameters: {
      scheduleIdList: scheduleIdList,
    },
    onSuccess,
    onFailure,
    onComplete,
  });
};

export const deleteReservation = ({ onSuccess, onFailure, onComplete }) => {
  if (typeof window === "object" && !window.PalmSystem) {
    console.log("LUNA SEND deleteReservation");
    return;
  }

  return new LS2Request().send({
    service: "luna://com.palm.db",
    method: "search",
    parameters: {
      query: {
        from: "com.webos.service.tvReservationAgent.info:1",
        orderBy: "startTime",
        filter: [{ prop: "reserveType", op: "=", val: 6 }], // 6 LG Shopping 전용.
      },
    },
    onSuccess,
    onFailure,
    onComplete,
  });
};

export const deleteOldDb8 = (kind, { onSuccess, onFailure, onComplete }) => {
  if (typeof window === "object" && !window.PalmSystem) {
    console.log("LUNA SEND deleteOldDb8");
    onSuccess && onSuccess();
    return;
  }

  const id = window.PalmSystem.identifier ?? appinfo.id;

  return new LS2Request().send({
    service: "luna://com.webos.service.db",
    method: "delKind",
    parameters: {
      id: id + ":" + kind,
    },
    onSuccess,
    onFailure,
    onComplete,
  });
};

export const checkFirstLaunch = ({ onSuccess, onFailure, onComplete }) => {
  if (typeof window === "object" && !window.PalmSystem) {
    console.log("LUNA SEND checkFirstLaunch");
    return;
  }

  const id = window.PalmSystem.identifier ?? appinfo.id;

  return new LS2Request().send({
    service: "luna://com.webos.service.db",
    method: "find",
    parameters: {
      query: {
        from: `${id}:20`,
        where: [{ prop: "type", op: "=", val: "app_init" }],
      },
    },
    onSuccess,
    onFailure,
    onComplete,
  });
};

export const saveFirstLaunchInfo = ({ onSuccess, onFailure, onComplete }) => {
  if (typeof window === "object" && !window.PalmSystem) {
    console.log("LUNA SEND saveFirstLaunchInfo");
    onSuccess({ returnValue: true });
    return;
  }

  const id = window.PalmSystem.identifier ?? appinfo.id;

  return new LS2Request().send({
    service: "luna://com.webos.service.db",
    method: "put",
    parameters: {
      object: [
        {
          _kind: `${id}:20`,
          type: "app_init",
          initialized: true,
          timestamp: new Date().toISOString(),
        },
      ],
    },
    onSuccess,
    onFailure,
    onComplete,
  });
};

export const disableNotification = ({ onSuccess, onFailure, onComplete }) => {
  if (typeof window === "object" && !window.PalmSystem) {
    console.log("LUNA SEND disableNotification");
    return;
  }

  return new LS2Request().send({
    service: "luna://com.webos.notification",
    method: "disable",
    parameters: {},
    onSuccess,
    onFailure,
    onComplete,
  });
};

export const enableNotification = ({ onSuccess, onFailure, onComplete }) => {
  if (typeof window === "object" && !window.PalmSystem) {
    console.log("LUNA SEND enableNotification");
    return;
  }

  return new LS2Request().send({
    service: "luna://com.webos.notification",
    method: "enable",
    parameters: {},
    onSuccess,
    onFailure,
    onComplete,
  });
};

export const getConnectionInfo = ({ onSuccess, onFailure, onComplete }) => {
  if (typeof window === "object" && !window.PalmSystem) {
    console.log("LUNA SEND disableConnectionInfo");
    return;
  } else {
    return new LS2Request().send({
      service: "luna://com.webos.service.connectionmanager",
      method: "getinfo",
      subscribe: false,
      parameters: {},
      onSuccess,
      onFailure,
      onComplete,
    });
  }
};

// Check system time availability
export const getSystemTime = ({ onSuccess, onFailure, onComplete }) => {
  if (typeof window === "object" && !window.PalmSystem) {
    console.log("LUNA SEND getSystemTime - mock environment");
    onSuccess({ returnValue: true, utc: Date.now() / 1000 });
    return;
  }

  return new LS2Request().send({
    service: "luna://com.webos.settingsservice",
    method: "getSystemSettings",
    subscribe: false,
    parameters: {
      category: "time",
      keys: ["autoClock"],
    },
    onSuccess: (res) => {
      console.log("LUNA SEND getSystemTime success", res);
      if (res && res.returnValue) {
        // If autoClock is available, try to get actual time
        new LS2Request().send({
          service: "luna://com.webos.service.systemservice",
          method: "clock/getTime",
          subscribe: false,
          parameters: {},
          onSuccess: (timeRes) => {
            console.log("LUNA SEND clock/getTime success", timeRes);
            onSuccess(timeRes);
          },
          onFailure: (timeErr) => {
            console.log("LUNA SEND clock/getTime failed", timeErr);
            // Fallback to settings response if getTime fails
            onSuccess(res);
          },
          onComplete,
        });
      } else {
        onFailure(res);
      }
    },
    onFailure,
    onComplete,
  });
};
