<template>
    <section class="flex flex-col flex-1 w-full gap-5 lg:flex-row">
        <Rooms
            v-if="chats.length > 0"
            :chats="chats"
            @changeActiveRoom="setSelectedChat"
            :active="selectedChat?.id"
            :is="is"
        />
        <Main :chat="selectedChat" :is="is" />
    </section>
</template>

<script>
import Rooms from "./Rooms.vue";
import Main from "./Main.vue";
import Echo from "laravel-echo";
import Pusher from "pusher-js";
export default {
    components: {
        Rooms,
        Main,
    },
    props: {
        chats: {
            type: Array,
            required: true,
        },
        is: {
            type: String,
            required: true,
        },
    },
    methods: {
        getChat(id) {
            const selected = this.chats.find((chat) => chat.id === id);
            if (selected) {
                return JSON.parse(JSON.stringify(selected));
            }
            return null;
        },
        setSelectedChat(id) {
            this.selectedChatId = Number.parseInt(id);
            this.selectedChat = this.getChat(this.selectedChatId);
        },
        updateSelectedChat() {
            this.selectedChat = this.getChat(this.selectedChatId);
        },
        initEcho() {
            window.Echo = new Echo({
                broadcaster: "pusher",
                key: this.$page.props?.pusher?.key,
                cluster: "eu",
                encrypted: true,
            });
        },
        updateRoom() {
            this.$nextTick(() => {
                if (this.selectedChat) {
                    if (this.currentRoom) window.Echo.leave(this.currentRoom);
                    this.currentRoom = `chat.${this.selectedChat.id}`;
                    const vm = this;
                    window.Echo.private(this.currentRoom).listen(
                        "ChatMessage",
                        (e) => {
                            if (
                                e.message.sender_uid !==
                                this.$page.props.current_user.id
                            )
                                vm.selectedChat.messages.push(e.message);
                        }
                    );
                }
            });
        },
    },
    data() {
        return {
            selectedChat: null,
            selectedChatId: null,
            currentRoom: null,
        };
    },
    created() {
        // get url params
        const urlParams = new URLSearchParams(window.location.search);
        const chatId = urlParams.get("chat");
        this.setSelectedChat(chatId ?? this.chats[0]?.id);
        this.initEcho();
    },
    mounted() {
        this.updateRoom();
    },
    watch: {
        selectedChat() {
            this.updateRoom();
        },
        chats() {
            this.updateSelectedChat();
        },
    },
    // beforeMount() {
    //     this.setSelectedChat(this.chats[0].id);
    // },
};
</script>
