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

    export let pixelfedFeed: string;

    const atomUrl = "https://pixelfed.scot/users/fbface.atom";

    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 feedSubtitle = doc.getElementsByTagName('subtitle')[0].textContent;
            const feedUpdated = doc.getElementsByTagName('updated')[0].textContent;

            // Get link to profile
            const feedProfile = doc.querySelector('link[rel="alternate"][type="text/html"]');
            const feedProfileLink = feedProfile ? feedProfile.getAttribute('url') : null;

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

            let entryArray: PixelfedFeed[] = [];

            for (let i = 0; i < entries.length; i++) {
                const entry = entries[i];
                const entryMediaContent = entry.getElementsByTagName('media:content')[0];
                const entryPixelfedUrl = entry.getElementsByTagName('link')[0];

                const feedItem: PixelfedFeed = {
                    title: entry.getElementsByTagName('title')[0].textContent,
                    updated: entry.getElementsByTagName('updated')[0].textContent,
                    imgUrl: entryMediaContent ? entryMediaContent.getAttribute('url') : null,
                    pixelfedUrl: entryPixelfedUrl ? entryPixelfedUrl.getAttribute('href') : null,
                }; 

                entryArray.push(feedItem);
            }

            const parsedFeed: AtomFeed = {
                title: feedTitle,
                subtitle: feedSubtitle,
                updated: feedUpdated,
                url: feedProfileLink,
                content: entryArray,
            }
            
            console.log(JSON.stringify(parsedFeed))
            return parsedFeed

        } catch (err) {
            console.error("Unable to load Pixelfed feed", err);
            throw new Error("Unable to load Pixelfed feed");
        }
    }
</script>
{#await loadFeed(pixelfedFeed)}
    <h5>Loading Pixelfed feed</h5>
{:then feedData}
    {#each feedData.content as feedItem}
        <EmptyCard>
            <p class="title">{feedItem.title?.split('|')[0]}</p>
            <p class="desc">{feedItem.title?.split('| ')[1].split('#')[0]}</p>
            <a href={feedItem.pixelfedUrl}>
                <img class="pixelfedImg" src="{feedItem.imgUrl}" alt="{feedItem.title}">
            </a>
            <p class="uploaded">Uploaded: {new Date(feedItem.updated).toLocaleString()}</p>
        </EmptyCard>
    {/each}
{:catch}
    <h5>Error connecting to Pixelfed</h5>
{/await}

<style>
    .pixelfedImg {
        width: 80%;
        max-width: 600px;
        margin: auto;
    }
    .title {
        text-align: center;
        margin: auto;
        font-weight: bolder;
        margin-bottom: 5px;
    }
    .uploaded {
        margin: 0;
        margin: auto;
        font-size: 14px;
    }
</style>