import React from "react";
import ReactDOM from "react-dom";
import LoggerService from "./loggerService";
import LoggerStore, { showFocusBTF } from "./src/stores/LoggerStore";
import App from "./src/app";
import ConfigClient from "../../clients/configClient";
import { System } from "../../common/system";

/**
 * Makes the LoggerService window visible
 */
const showConsole = () => {
	const finWindow = System.Window.getCurrent();
	showFocusBTF(finWindow);
};

/**
 * Decides whether to immediately display the Central Logger, or display Central Logger automatically
 * upon an error. This behavior can be set either as a user preference (by checking boxes in the
 * Central Logger UI) or as a config (by adding entries to finsemble.preferences.loggerService).
 */
const maybeShowCentralLogger = async () => {
	const { data: values } = await ConfigClient.getPreferences();
	const showOnStartupPreference = values?.["finsemble.preferences.loggerService.showOnStartup"];
	const showOnErrorPreference = values?.["finsemble.preferences.loggerService.showOnError"];
	const { data: showOnStartupConfig } = await ConfigClient.getValue(
		"finsemble.preferences.loggerService.showOnStartup"
	);
	const { data: showOnErrorConfig } = await ConfigClient.getValue("finsemble.preferences.loggerService.showOnError");

	const showOnStartup = showOnStartupPreference ?? showOnStartupConfig ?? false;
	const showOnError = showOnErrorPreference ?? showOnErrorConfig ?? false;

	// The second "false" parameter prevents the store from setting this value as a preference
	LoggerStore.setShowOnStartup(showOnStartup, false);
	LoggerStore.setShowOnError(showOnError, false);
	if (showOnStartup) showConsole();
};

/**
 * When safe, initialize the LoggerStore and get preferences
 */
const main = async () => {
	LoggerStore.initialize();
	maybeShowCentralLogger();
	// Sets the window to hide rather than close (hideOnClose) when the end user closes from the window frame
	const finWindow = System.Window.getCurrent();
	finWindow.addEventListener("close-requested", () => {
		finWindow.hide();
	});
};

main();

// Allow developers to display the central logger from http://localhost:9090
(window as any).showConsole = showConsole;

// e2e test require access to the logger store to produce debugging information (via Selenium)
// See central_logger.py
(window as any).loggerServiceTestRig = {
	loggerStore: LoggerStore,
};

const LoggerServiceUI = () => <App />;

ReactDOM.render(<LoggerServiceUI />, document.getElementById("LoggerServiceUI-tsx"));

// This line is necessary for the service to start, otherwise webpack thinks it's not being used and doesn't run the file InteropService.ts
const loggerService = LoggerService;
