---
import moment from "moment/moment";
import {CollectionEntry} from "astro:content";
import {astroI18n, createGetStaticPaths, t} from "astro-i18n";
import {getCollection} from "astro:content";
import PageLayout from "../../../layouts/PageLayout.astro";
import {l} from "../../../util/util";
import {capitalize} from "../../../components/admin/util";
import PostComponent from "../../../components/PostComponent.astro";

export const getStaticPaths = createGetStaticPaths(async () => {
    const posts = (await getCollection('announcements', entry => entry.id.split("/")[0] === astroI18n.locale))
            .sort((a, b) => moment(b.data.created).unix() - moment(a.data.created).unix());

    let groupedByTags: Record<string, CollectionEntry<'announcements'>[]> = {}
    posts.forEach(post => {
        post.data.tags.forEach(tag => {
            if (!groupedByTags[tag]) {
                groupedByTags[tag] = []
            }
            groupedByTags[tag].push(post)
        })
    })

    return Object.keys(groupedByTags).map(tag => ({
        params: {
            tag: tag
        },
        props: {
            posts: groupedByTags[tag],
            tag: tag
        }
    }))
})

interface Props {
    posts: CollectionEntry<'announcements'>[]
    tag: string
}

const { posts, tag } = Astro.props;
---

<PageLayout title={t("tag.title", {tag: capitalize(tag)})}>
    {posts.map((post, index) => (
        <div>
            <PostComponent post={post} />
            {index !== posts.length - 1 && <hr/>}
        </div>
    ))}
</PageLayout>
