import { atom, computed, map, type ReadableAtom } from "nanostores"
import type { AlertMap, ChartTimes, SystemRecord, UpdateInfo, UserSettings } from "@/types"
import { pb } from "./api"
import { Unit } from "./enums"
export const defaultLayoutWidth = 1600
export const $authenticated = atom(pb.authStore.isValid)
export const $allSystemsByName = map<Record<string, SystemRecord>>({})
export const $allSystemsById = map<Record<string, SystemRecord>>({})
export const $upSystems = map<Record<string, SystemRecord>>({})
export const $downSystems = map<Record<string, SystemRecord>>({})
export const $pausedSystems = map<Record<string, SystemRecord>>({})
export const $systems: ReadableAtom<SystemRecord[]> = computed($allSystemsById, Object.values)
export const $systemsLoaded = atom(false)
export const $alerts = map<AlertMap>({})
export const $publicKey = atom("")
export const $newVersion = atom<UpdateInfo | undefined>()
export const defaultChartTime: ChartTimes = "1h"
export const $chartTime = atom<ChartTimes>(defaultChartTime)
export const $maxValues = atom(false)
const logTimestampsKey = "besz-log-ts"
export const $showLogTimestamps = atom<boolean>(JSON.parse(globalThis.localStorage?.getItem(logTimestampsKey) ?? "true"))
export function toggleLogTimestamps() {
const next = !$showLogTimestamps.get()
$showLogTimestamps.set(next)
globalThis.localStorage?.setItem(logTimestampsKey, JSON.stringify(next))
}
export const $userSettings = map<UserSettings>({
chartTime: defaultChartTime,
emails: [pb.authStore.record?.email || ""],
unitNet: Unit.Bytes,
unitTemp: Unit.Celsius,
})
export function getUserChartTime(settings: UserSettings = $userSettings.get()): ChartTimes {
return settings.chartTime || defaultChartTime
}
* Apply settings loaded from the database, including the default chart time.
* Other settings writes don't touch $chartTime so they can't reset the active chart range.
*/
export function hydrateUserSettings(settings: UserSettings) {
$userSettings.set(settings)
$chartTime.set(getUserChartTime(settings))
}
export const $containerFilter = atom("")
export const $temperatureFilter = atom("")
export const $monitorFilter = atom("")
export const $fanFilter = atom("")
export const $copyContent = atom("")
export const $direction = atom<"ltr" | "rtl">("ltr")