import { init } from "@sentry/react-native";
import { Component } from "react";
import codePush from "react-native-code-push";
import { SentryConstants } from "./App/common/constants/SentryConstants";
import { logToSentry } from "./App/common/hooks/useSentryLogging";
import { CtaData } from "./App/common/interface";
import RnApp from "./App/common/navigator/RnAppCreator";
import {
  getBuildConfigDetails,
  setBuildConfigDetails,
} from "./App/common/utilities/CacheUtils";

init({
  dsn: SentryConstants.SENTRY_DSN,
  environment: SentryConstants.SENTRY_ENVIRONMENT_PRODUCTION,
});

export default class App extends Component<{}> {
  checkForUpdates = async () => {
    let flavor: string | undefined;
    getBuildConfigDetails().then(res => {
      flavor = res?.baseUrl;
    });
    await codePush.sync(
      {
        installMode: codePush.InstallMode.ON_NEXT_RESUME,
        mandatoryInstallMode: codePush.InstallMode.IMMEDIATE,
      },
      status => {
        this.onCodepushStatusChange(status);
      },
    );
  };

  onCodepushStatusChange = (status: codePush.SyncStatus) => {
    switch (status) {
      case codePush.SyncStatus.UPDATE_IGNORED:
        logToSentry(
          `Codepush Ignored | Status: ${status} | MethodName: onCodepushStatusChange`,
        );
        break;
      case codePush.SyncStatus.UNKNOWN_ERROR:
        logToSentry(
          `Codepush Failed | Status: ${status} | MethodName: onCodepushStatusChange`,
        );
    }
  };

  getInitialCta = (): CtaData | undefined => {
    const { CtaData } = this.props as any;

    if (!CtaData) {
      logToSentry(
        `CtaData is missing or invalid: ${CtaData} | MethodName: getInitialCta`,
      );
      return;
    }

    try {
      const cta = JSON.parse(CtaData) as CtaData;
      return cta;
    } catch (error) {
      logToSentry(
        `Error parsing CtaData: ${CtaData} | Error: ${error} | MethodName: getInitialCta`,
      );
      return;
    }
  };

  override componentDidMount(): void {
    setBuildConfigDetails();
    this.checkForUpdates();
  }

  override render() {
    const cta = this.getInitialCta();
    return cta ? RnApp.create(cta) : <></>;
  }
}
