pragma Singleton

import Quickshell
import Quickshell.Io
import Quickshell.Services.UPower
import ZShell.Config
import qs.Services
import qs.Paths

Singleton {
	id: root

	readonly property list<var> allPeripherals: [...logiDevices, ...upowerDevices.filter(d => !Battery.logiDevices.some(l => l.nativePath === d.nativePath))]
	readonly property real currentPerc: UPower.displayDevice.percentage
	readonly property var deviceState: UPower.displayDevice.state
	readonly property string deviceStateString: UPowerDeviceState.toString(deviceState)
	readonly property bool isLaptop: UPower.displayDevice.isLaptopBattery
	readonly property alias logiDevices: adapter.devices
	readonly property var lowestPeripheral: allPeripherals.reduce((lowest, current) => current.percentage < lowest.percentage ? current : lowest)
	readonly property bool onBattery: UPower.onBattery
	readonly property bool ready: UPower.displayDevice.ready
	readonly property real timeToEmpty: UPower.displayDevice.timeToEmpty
	readonly property real timeToFull: UPower.displayDevice.timeToFull
	readonly property list<UPowerDevice> upowerDevices: UPower.devices.values.filter(d => d.state !== UPowerDeviceState.Unknown)

	function getColors(percentage: real, state: string): var {
		if (state === "charging" || state === "full" || state === "recharging")
			return {
				fg: Colors.swapRG(Colors.palette.m3error),
				bg: Colors.swapRG(Colors.palette.m3onError)
			};
		else if (percentage <= 0.2)
			return {
				fg: Colors.palette.m3error,
				bg: Colors.palette.m3onError
			};
		else
			return {
				fg: Colors.palette.m3tertiary,
				bg: Colors.palette.m3onTertiary
			};
	}

	function startDaemon(): void {
		Quickshell.execDetached(["zshell-cli", "battery", "daemon"]);
	}

	FileView {
		id: fileView

		path: `${Paths.cache}/battery.json`
		watchChanges: true

		onFileChanged: reload()

		JsonAdapter {
			id: adapter

			property list<var> devices: []
			property real updated: 0.0
		}
	}
}
