import { merge } from "lodash";
import Paths from "./path";
import { readTomlFile, writeTomlFile } from "./utils/toml";

export const defaultSettings = {
  background: {
    background_color: "#202124" as string,
    background_image_path: "" as string,
  },
  style: {
    accent_color: "#8ab4f8" as string,
    dark_mode: true as boolean,
    font_family: "monospace" as string,
    font_scaling: 100,
    radius: 8 as number,
    transition_duration: 200 as number,
    window_height: 80 as number,
    window_width: 400 as number,
  },
  window: {
    maximize_button: false as boolean,
    minimize_button: false as boolean,
    start_fullscreen: false as boolean, // TODO: this should be true on prod
  },
};

export type SettingsType = typeof defaultSettings;

export const readConfigFile = async (): Promise<SettingsType> => {
  let existingData: SettingsType = defaultSettings;

  try {
    // try to read the config file
    await Paths.initialize();
    const data = await readTomlFile<SettingsType>(Paths.getPath("configDirectory") + "config.toml");
    if (data) {
      existingData = data;
      console.log("existing data");
      console.log(existingData);
    }
  } catch (error) {
    // file does not exist, called function will throw error
    console.error(`Failed to read settings file: ${error}, using default settings.`);
    existingData = defaultSettings;
  }

  // merge the existing data with the default settings
  // existing data will overwrite the default settings for the properties that exist
  const mergedSettings = merge({}, defaultSettings, existingData);

  return mergedSettings;
};

export const writeConfigFile = async (settingsValues: SettingsType): Promise<void> => {
  await writeTomlFile<SettingsType>(Paths.getPath("configDirectory") + "config.toml", settingsValues);
  console.debug("Settings file written successfully.");
};
