/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2026 metamuffin <metamuffin.org>
*/

use crate::{
    RenderInfo,
    format::{format_duration, format_duration_long, format_size},
};
use jellycommon::{jellyobject::Object, *};
use jellyui_locale::tr;
use markup::raw;

markup::define! {
    StatText<'a>(ri: &'a RenderInfo<'a>, stat: Object<'a>) {
        h1 { @tr(ri.lang, "stats.title") }
        p { @raw(tr(ri.lang, "stats.count")
            .replace("{count}", &format!("<b>{}</b>", stat.get(STAT_COUNT).unwrap_or_default()))
        )}
        p { @raw(tr(ri.lang, "stats.runtime")
            .replace("{dur}", &format!("<b>{}</b>", format_duration_long(ri.lang, stat.get(STAT_TOTAL_DURATION).unwrap_or_default())))
            .replace("{size}", &format!("<b>{}</b>", format_size(stat.get(STAT_TOTAL_SIZE).unwrap_or_default())))
        )}
        p { @raw(tr(ri.lang, "stats.average")
            .replace("{dur}", &format!("<b>{}</b>",  format_duration(stat.get(STAT_TOTAL_DURATION).unwrap_or_default() / stat.get(STAT_COUNT).unwrap_or_default() as f64)))
            .replace("{size}", &format!("<b>{}</b>", format_size(stat.get(STAT_TOTAL_SIZE).unwrap_or_default() / stat.get(STAT_COUNT).unwrap_or_default())))
        )}
    }
    StatGroup<'a>(ri: &'a RenderInfo<'a>, statgroup: Object<'a>) {
        h2 { @tr(ri.lang, statgroup.get(STATGROUP_TITLE).unwrap_or_default()) }
        table.striped {
            tr {
                th { @tr(ri.lang, "stats.by_kind.kind") }
                th { @tr(ri.lang, "stats.by_kind.count") }
                th { @tr(ri.lang, "stats.by_kind.total_size") }
                th { @tr(ri.lang, "stats.by_kind.total_runtime") }
                th { @tr(ri.lang, "stats.by_kind.average_size") }
                th { @tr(ri.lang, "stats.by_kind.average_runtime") }
                th { @tr(ri.lang, "stats.by_kind.max_size") }
                th { @tr(ri.lang, "stats.by_kind.max_runtime") }
            }
            @for stat in statgroup.iter(STATGROUP_BIN) { tr {
                td { @tr(ri.lang, stat.get(STAT_NAME).unwrap_or_default()) }
                td { @stat.get(STAT_COUNT).unwrap_or_default() }
                td { @format_size(stat.get(STAT_TOTAL_SIZE).unwrap_or_default()) }
                td { @format_duration(stat.get(STAT_TOTAL_DURATION).unwrap_or_default()) }
                td { @format_size(stat.get(STAT_TOTAL_SIZE).unwrap_or_default() / stat.get(STAT_COUNT).unwrap_or_default()) }
                td { @format_duration(stat.get(STAT_TOTAL_DURATION).unwrap_or_default() / stat.get(STAT_COUNT).unwrap_or_default() as f64) }
                td { @format_size(stat.get(STAT_MAX_SIZE).unwrap_or_default()) }
                td { @format_duration(stat.get(STAT_MAX_DURATION).unwrap_or_default()) }
            }}
        }
    }
}
