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

const store = useStore();
const route = useRoute();
const messageIdView = ref(-1);
const message = ref(undefined);
const id = ref(parseInt(route.params.id));
let room;
onBeforeMount(async () => {
    store.commit("setActiveRoom", id.value);
    room = store.getters.room(id.value);
});

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

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

function openMessageView(id) {
    messageIdView.value = id;
    message.value = room?.messages.find((message) => message.id == id);
}
</script>

<template>
    <div id="main">
        <Header :id="id" :room="room"></Header>
        <div id="RoomViewBody">
            <div class="content">
                <Message
                    v-for="(message, index) in room?.messages"
                    :key="index"
                    :msg="message"
                    :members="room?.members"
                    @open-message-view="(id) => openMessageView(id)"
                />
            </div>
            <div id="composer" v-if="shouldDisplayComposer()">COMPOSER</div>
        </div>
        <MessageViewModal :message="message" :messageId="messageIdView" @close="() => openMessageView(-1)" />
    </div>
</template>

<style scoped>
#main {
    background-color: var(--primary-background);
    color: var(--primary-text);
    width: 100%;
}

#RoomViewBody {
    display: flex;
    flex-direction: column;
    height: 100%;
}

#composer {
    position: absolute;
    bottom: 0;
    width: 100%;
    padding-top: 10px;

    height: 35px;
    background-color: red;
}

.content {
    display: flex;
    flex-direction: column-reverse;
    overflow: auto;
    margin-bottom: 60px;
}
</style>
