<script lang="ts">
    import EmptyCard from "$lib/card-collections/cards/EmptyCard.svelte";
	import { parse } from "path";
    import type { AtomFeed, GiteaFeed } from "./feedTypes";

    export let giteaFeed: string | undefined;

    async function loadFeed(feed: string) {
        try {
            const parser = new DOMParser();
            const doc = parser.parseFromString(feed, "text/xml");

            const feedTitle = doc.getElementsByTagName('title')[0].textContent;
            const feedUpdated = doc.getElementsByTagName('pubDate')[0].textContent;

            // Get link to profile
            const feedLink = doc.getElementsByTagName('link')[0].textContent;

            // Parse feed entries
            const entries = doc.getElementsByTagName('item');

            let entryArray: GiteaFeed[] = [];

            for (let i = 0; i < entries.length; i++) {
                const entry = entries[i];
                const entryTitle = entry.getElementsByTagName('title')[0].textContent;

                const feedItem: GiteaFeed = {
                    title: entryTitle
                }

                entryArray.push(feedItem);
            }

            const parsedFeed: AtomFeed<GiteaFeed> = {
                title: feedTitle,
                subtitle: "Gitea Feed",
                updated: feedUpdated,
                url: feedLink,
                content: entryArray
            }

            return parsedFeed
        } catch (err) {
            console.error("Unable to load Pixelfed feed", err);
            throw new Error("Unable to load Pixelfed feed");
        }
    }
</script>

{#await loadFeed(giteaFeed)}
    <h5>Loading Gitea Feed</h5>    
{:then feedData}
    {#each feedData.content as feedItem}
        <EmptyCard>
            <p>{@html feedItem.title}</p>
        </EmptyCard>
    {/each}
{:catch}
    <h5>Error connecting to Gitea</h5>
{/await}