pragma Singleton

import Quickshell
import QtQuick
import qs.Modules
import qs.Helpers
import ZShell.Config
import qs.Paths
import qs.Services

Singleton {
	id: root

	readonly property int darkEnd: Config.colors.scheduleDarkEnd
	readonly property int darkStart: Config.colors.scheduleDarkStart
	readonly property bool enabled: Config.colors.scheduleDark && Config.colors.schemeGen

	function applyDarkMode() {
		Quickshell.execDetached(["zshell-cli", "scheme", "generate", "--mode", "dark"]);

		Config.colors.mode = "dark";

		Quickshell.execDetached(["gsettings", "set", "org.gnome.desktop.interface", "color-scheme", "'prefer-dark'"]);

		Quickshell.execDetached(["sh", "-c", `sed -i 's/color_scheme_path=\\(.*\\)Light.colors/color_scheme_path=\\1Dark.colors/' ${Paths.home}/.config/qt6ct/qt6ct.conf`]);

		Quickshell.execDetached(["sed", "-i", "'s/\\(vim.cmd.colorscheme \\).*/\\1\"tokyodark\"/'", "~/.config/nvim/lua/config/load-colorscheme.lua"]);
	}

	function applyLightMode() {
		Quickshell.execDetached(["zshell-cli", "scheme", "generate", "--mode", "light"]);

		Config.colors.mode = "light";

		Quickshell.execDetached(["gsettings", "set", "org.gnome.desktop.interface", "color-scheme", "'prefer-light'"]);

		Quickshell.execDetached(["sh", "-c", `sed -i 's/color_scheme_path=\\(.*\\)Dark.colors/color_scheme_path=\\1Light.colors/' ${Paths.home}/.config/qt6ct/qt6ct.conf`]);

		if (Config.colors.neovimColors)
			Quickshell.execDetached(["sed", "-i", "'s/\\(vim.cmd.colorscheme \\).*/\\1\"onelight\"/'", "~/.config/nvim/lua/config/load-colorscheme.lua"]);
	}

	function checkStartup() {
		if (!root.enabled)
			return;

		var now = new Date();
		var nowMinutes = now.getHours() * 60 + now.getMinutes();

		var isDarkTime;

		if (root.darkStart <= root.darkEnd) {
			isDarkTime = (nowMinutes >= root.darkStart && nowMinutes < root.darkEnd);
		} else {
			isDarkTime = (nowMinutes >= root.darkStart || nowMinutes < root.darkEnd);
		}

		if (isDarkTime) {
			if (Colors.light)
				root.applyDarkMode();
		} else {
			if (!Colors.light)
				root.applyLightMode();
		}
	}

	Timer {
		id: darkModeTimer

		interval: 5000
		repeat: true
		running: true

		onTriggered: {
			if (!root.enabled)
				return;

			var now = new Date();
			var nowMinutes = now.getHours() * 60 + now.getMinutes();

			var isDarkTime;

			if (root.darkStart <= root.darkEnd) {
				isDarkTime = (nowMinutes >= root.darkStart && nowMinutes < root.darkEnd);
			} else {
				isDarkTime = (nowMinutes >= root.darkStart || nowMinutes < root.darkEnd);
			}

			if (isDarkTime) {
				if (Colors.light)
					root.applyDarkMode();
			} else {
				if (!Colors.light)
					root.applyLightMode();
			}
		}
	}
}
