use windows::core::PCWSTR;
use windows::Win32::Foundation::{FILETIME, SYSTEMTIME};
use windows::Win32::Globalization::{
GetLocaleInfoEx, GetTimeFormatEx, LOCALE_S1159, LOCALE_S2359, LOCALE_SSHORTTIME, LOCALE_STIME,
TIME_FORMAT_FLAGS,
};
use windows::Win32::System::Time::{
FileTimeToSystemTime, SystemTimeToFileTime, SystemTimeToTzSpecificLocalTime,
TzSpecificLocalTimeToSystemTime,
};
use crate::lock::settings::{weekday, ClockTime, Day, MINUTE};
use crate::lock::Zone;
const DAY_MS: i64 = 24 * 60 * MINUTE;
const UNIX_EPOCH_MS: i64 = 11_644_473_600_000;
pub const DAY_NAMES: [&str; 7] = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
];
pub struct Local;
impl Zone for Local {
fn instant(&self, day: Day, minutes: u16) -> i64 {
let wanted = day * DAY_MS + i64::from(minutes) * MINUTE;
let utc = local_to_utc(wanted).unwrap_or(wanted);
let shown = utc_to_local(utc).unwrap_or(wanted);
utc + (wanted - shown).max(0)
}
fn day_of(&self, wall: i64) -> Day {
utc_to_local(wall).unwrap_or(wall).div_euclid(DAY_MS)
}
}
fn to_system(ms: i64) -> Option<SYSTEMTIME> {
let ticks = ((ms + UNIX_EPOCH_MS) * 10_000) as u64;
let file = FILETIME {
dwLowDateTime: ticks as u32,
dwHighDateTime: (ticks >> 32) as u32,
};
let mut out = SYSTEMTIME::default();
unsafe { FileTimeToSystemTime(&file, &mut out) }.ok()?;
Some(out)
}
fn from_system(time: &SYSTEMTIME) -> Option<i64> {
let mut file = FILETIME::default();
unsafe { SystemTimeToFileTime(time, &mut file) }.ok()?;
let ticks = (u64::from(file.dwHighDateTime) << 32) | u64::from(file.dwLowDateTime);
Some((ticks / 10_000) as i64 - UNIX_EPOCH_MS)
}
fn local_to_utc(local: i64) -> Option<i64> {
let mut utc = SYSTEMTIME::default();
unsafe { TzSpecificLocalTimeToSystemTime(None, &to_system(local)?, &mut utc) }.ok()?;
from_system(&utc)
}
fn utc_to_local(utc: i64) -> Option<i64> {
let mut local = SYSTEMTIME::default();
unsafe { SystemTimeToTzSpecificLocalTime(None, &to_system(utc)?, &mut local) }.ok()?;
from_system(&local)
}
fn locale(what: u32) -> String {
let mut buffer = [0u16; 80];
let n = unsafe { GetLocaleInfoEx(PCWSTR::null(), what, Some(&mut buffer)) };
String::from_utf16_lossy(&buffer[..(n as usize).saturating_sub(1)])
}
pub fn format_instant(wall: i64) -> String {
let local = utc_to_local(wall).unwrap_or(wall).rem_euclid(DAY_MS);
format_time(ClockTime((local / MINUTE) as u16))
}
pub fn format_when(wall: i64, now: i64) -> String {
let day = Local.day_of(wall);
let time = format_instant(wall);
let name = DAY_NAMES[weekday(day)];
match day - Local.day_of(now) {
0 => time,
7.. => format!("next {name} {time}"),
_ => format!("{name} {time}"),
}
}
pub fn format_time(time: ClockTime) -> String {
let (h, m) = (time.0 / 60, time.0 % 60);
let system = SYSTEMTIME {
wYear: 2000,
wMonth: 1,
wDay: 1,
wHour: h,
wMinute: m,
..Default::default()
};
let pattern: Vec<u16> = locale(LOCALE_SSHORTTIME)
.encode_utf16()
.chain([0])
.collect();
let mut buffer = [0u16; 80];
let n = unsafe {
GetTimeFormatEx(
PCWSTR::null(),
TIME_FORMAT_FLAGS(0),
Some(&system),
PCWSTR(pattern.as_ptr()),
Some(&mut buffer),
)
};
match n {
n if n > 1 => String::from_utf16_lossy(&buffer[..n as usize - 1]),
_ => format!("{h}:{m:02}"),
}
}
pub fn parse_time(text: &str) -> Option<ClockTime> {
let mut rest = text.trim().to_lowercase();
let mut afternoon = None;
let markers = [
(locale(LOCALE_S1159), false),
(locale(LOCALE_S2359), true),
("am".into(), false),
("pm".into(), true),
];
for (marker, pm) in markers {
let marker = marker.to_lowercase();
if marker.is_empty() || afternoon.is_some() {
continue;
}
let without = rest
.strip_suffix(&marker)
.or_else(|| rest.strip_prefix(&marker))
.map(|r| r.trim().to_string());
if let Some(without) = without {
rest = without;
afternoon = Some(pm);
}
}
let separator = locale(LOCALE_STIME).to_lowercase();
let (h, m) = rest
.split_once(':')
.or_else(|| rest.split_once(separator.as_str()))?;
let (h, m): (u16, u16) = (h.trim().parse().ok()?, m.trim().parse().ok()?);
let h = match afternoon {
None if h < 24 => h,
Some(pm) if (1..=12).contains(&h) => h % 12 + if pm { 12 } else { 0 },
_ => return None,
};
(m < 60).then_some(ClockTime(h * 60 + m))
}