<script>
    import { afterUpdate, beforeUpdate } from "svelte";
    import { messagesStoreProvider } from "../../../stores.js";

    export let channelId;
    let scrollTarget;
    let shouldAutoscroll = false;
    let lastScrollHeight = null;

    $: messages = messagesStoreProvider.getStore(channelId);

    beforeUpdate(() => {
        shouldAutoscroll = scrollTarget && (scrollTarget.offsetHeight + scrollTarget.scrollTop) > (scrollTarget.scrollHeight - 20);
    });

    afterUpdate(() => {
        // hacky way to preserve scroll position when messages are pushed back
        if (lastScrollHeight) {
            scrollTarget.scrollTop =  scrollTarget.scrollHeight - lastScrollHeight;
            lastScrollHeight = null;
            return;
        }
        if (shouldAutoscroll && scrollTarget) {
            scrollTarget.scrollTo(0, scrollTarget.scrollHeight);
        }
    });

    const onScroll = (e) => {
        const { scrollTop, offsetHeight, scrollHeight } = e.target;
        if ((scrollTop + offsetHeight) >= scrollHeight) { // user scrolled to bottom
            messages.setIsCollectingOldMessages(true);
        } else {
            if (scrollTop === 0) {
                // load older messages if the user scrolls to the top.
                // save the current scroll height if the server returned any messages,
                // before commiting them to the store. this is to provide the jank scroll height
                // preservation
                messages.loadOlderMessages(() => {
                    if (scrollTarget)
                        lastScrollHeight = scrollTarget.scrollHeight;
                });
            }
            messages.setIsCollectingOldMessages(false);
        }
    };

</script>

<style>
    .messages-container {
        padding: var(--space-sm);
        height: 100%;
        width: 100%;
        flex-grow: 0;
        overflow-y: auto;
        background-color: var(--background-color-1);
    }

    .pending {
        color: var(--foreground-color-2);
    }
</style>

<div class="messages-container" on:scroll={ onScroll } bind:this={ scrollTarget }>
    {#each $messages as message (message.id)}
        <div>
            <b>{ message.author_username }</b>
            <span class:pending={ message._isPending }>{ message.content }</span>
        </div>
    {/each}
</div>
