use crate::app::App;
use crate::i18n::i18n;
use crate::util::ClockFormat;
use chrono::{DateTime, Datelike, Local, NaiveTime, TimeDelta, TimeZone, Utc};

pub struct DateUtil;

impl DateUtil {
    pub fn format_time(datetime: &DateTime<Utc>) -> String {
        let local_datetime = datetime.with_timezone(&Local);
        let clock_format = App::default().desktop_settings().clock_format();

        if clock_format == ClockFormat::F12H {
            format!("{}", local_datetime.format("%I:%M %p"))
        } else {
            format!("{}", local_datetime.format("%k:%M"))
        }
    }

    pub fn format_date(datetime: &DateTime<Utc>) -> String {
        let local_date = datetime.with_timezone(&Local).date_naive();
        let now = Local::now().date_naive();
        let days_since = now - local_date;
        let same_year = local_date.year() == now.year();
        let humand_readable = local_date.format("%A, %B %d"); // e.g. "Tuesday, March 5"

        if now == local_date {
            i18n("Today")
        } else if days_since == TimeDelta::try_days(1).unwrap() {
            i18n("Yesterday")
        } else if same_year {
            format!("{humand_readable}")
        } else {
            format!("{humand_readable}, {}", local_date.format("%Y"))
        }
    }

    pub fn today_start_end() -> (DateTime<Utc>, DateTime<Utc>) {
        let now = Local::now();
        let start_local = now.with_time(NaiveTime::from_hms_opt(0, 0, 0).unwrap()).unwrap();
        let start_utc_naive = start_local.naive_utc();
        let start = Utc.from_local_datetime(&start_utc_naive).unwrap();

        let end_local = now.with_time(NaiveTime::from_hms_opt(23, 59, 59).unwrap()).unwrap();
        let end_utc_naive = end_local.naive_utc();
        let end = Utc.from_local_datetime(&end_utc_naive).unwrap();

        (start, end)
    }
}
