<script>
    import request from "../request";
    import { apiRoute } from "../storage";
    import { messagesStoreProvider, overlayStore, userInfoStore } from "../stores";

    export let channel;
    let messageInput = "";

    $: messages = messagesStoreProvider.getStore(channel.id);

    const onKeydown = async (e) => {
        if (e.code !== "Enter")
            return;

        if (messageInput.trim() === "" || !$userInfoStore)
            return;

        // optimistically add message to store
        const optimisticMessageId = Math.floor(Math.random() * 999999);
        const optimisticMessage = {
            id: optimisticMessageId,
            content: messageInput,
            channel_id: channel.id,
            author_id: $userInfoStore.id,
            author_username: $userInfoStore.username,
            created_at: Date.now().toString(),
            _isPending: true
        };
        messages.addMessage(optimisticMessage);
        messageInput = "";

        const res = await request("POST", apiRoute(`channels/${channel.id}/messages`), true, {
            content: optimisticMessage.content
        });
        
        if (res.success && res.ok) {
            messages.setMessage(optimisticMessageId, res.json);
        } else {
            messages.deleteMessage({
                id: optimisticMessageId
            });
            overlayStore.open("toast", {
                message: "Couldn't send message"
            });
        }
    };
</script>

<style>
    .message-input-container {
        width: 100%;
        padding: var(--space-norm);
    }

    .message-input {
        height: 3em;
        width: 100%;
        background-color : var(--background-color-2);
        border: none;
        color: currentColor;
        border-radius: var(--radius-md);
        padding: var(--space-sm);
        font-size: inherit;
        line-height: inherit;
    }

    .message-input::placeholder {
        color: var(--foreground-color-3);
    }
</style>

<div class="message-input-container">
    <input
        placeholder={`Send something interesting to #${channel.name}`}
        type="text"
        class="message-input"
        on:keydown={ onKeydown }
        bind:value={ messageInput }
    >
</div>
