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

export const defaultSettings = {
  display: {
    dark_mode: true as boolean,
    accent_color: "#8ab4f8" as string,
    transition_duration: 200 as number,
    radius: 8 as number,
    window_height: 60 as number,
    window_width: 400 as number,
    font_family: "monospace" as string,
    font_scaling: 100,
  },
  window: {
    minimize_button: false as boolean,
    maximize_button: false as boolean,
  },
};

export type SettingsType = typeof defaultSettings;

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

  try {
    // try to read the config file
    const data = await readTomlFile<SettingsType>(Paths.getPath("configDirectory") + "config.toml");
    if (data) {
      existingData = data;
    }
  } 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 = { ...defaultSettings, ...existingData };

  return mergedSettings;
};

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