<script setup>
import { useStore } from "vuex";
import { useRoute, onBeforeRouteUpdate } from "vue-router";
import { onBeforeMount, provide, ref } from "vue";
import { RoomType } from "@/store/models/model";
import Header from "./Header.vue";
import Message from "../../components/structure/message/Message.vue";
import MessageViewModal from "@/components/modals/MessageViewModal.vue";
import Composer from "@/components/structure/message/Composer.vue";

const store = useStore();
const route = useRoute();
const messageIdView = ref(-1);
const message = ref(undefined);
const messages = ref([]);
const id = ref(parseInt(route.params.id));
let room = ref();

onBeforeMount(async () => {
    store.commit("setActiveRoom", id.value);
    room.value = store.getters.room(id.value);
    messages.value = store.getters.messages(room.value?.id);
    console.log(room.value);
});

onBeforeRouteUpdate(async (to, from) => {
    if (to.params.id !== from.params.id) {
        id.value = parseInt(to.params.id);
        store.commit("setActiveRoom", id.value);
        room.value = await store.getters.room(id.value);
        messages.value = store.getters.messages(room.value?.id);

        console.log(room.value);
    }
});

const shouldDisplayComposer = () => {
    if (!room?.value) return false;
    return (
        room.value.roomType == RoomType.THREAD ||
        room.value.roomType == RoomType.GROUP ||
        room.value.roomType == RoomType.DM
    );
};

function openMessageView(messageId) {
    messageIdView.value = messageId;
    if (messageId === -1) return;
    message.value = store.getters.message(room.value.id, messageId);
}

const shouldBeCompact = (index) => {
    // show last three messages
    if (messages.value?.length - 4 < index) return false;
    return true;
};

provide("room", room);
</script>

<template>
    <div class="container">
        <Header :id="id" :room="room"></Header>
        <div class="messages">
            <Message
                v-for="(message, index) in messages"
                :key="index"
                :msg="message"
                :members="room?.members"
                :compact="shouldBeCompact(index)"
                @open-message-view="(id) => openMessageView(id)"
            />
        </div>
        <Composer v-if="shouldDisplayComposer() || true" />
        <MessageViewModal :message="message" :messageId="messageIdView" @close="() => openMessageView(-1)" />
    </div>
</template>

<style scoped>
.container {
    display: flex;
    flex-direction: column;
    background-color: var(--primary-background);
    color: var(--primary-text);
    height: 100vh;
    width: 100%;
}

.messages {
    flex-grow: 1;
    overflow: auto;
}
</style>
