/*
 * Copyright (c) 2022.
 * Author Peter Placzek (tada5hi)
 * For the full copyright and license information,
 * view the LICENSE file that was distributed with this source code.
 */

import {SocketInterface,} from "../../../modules/socket";
import {useChatRoom} from "./room";
import {AppContext} from "../../index";
import {createChatSocketEventHandler} from "./event";
import {createChatRoomSocketEventHandler} from "./event/room";
import createAuthMiddleware from "../../auth/socket/middleware";
import {getRepository} from "typeorm";
import {ChatRoom} from "@chamesu/common/domains/chat/room";
import {ChatMember} from "@chamesu/common/domains/chat/member";

export default function createSocketChatApp(ctx: AppContext) {
    const room = useChatRoom(
        ctx,
        async function (roomId: string){
            return await getRepository(ChatRoom).findOne(roomId);
        },
        async function (roomId: string, userId: number){
            return await getRepository(ChatMember).findOne({room_id: roomId, user_id: userId});
        }
    );

    room.checkIntegrity().then(r => r);

    room.ctx.socketNamespace.use(createAuthMiddleware());
    room.ctx.socketNamespace
        .on('connection', (socket: SocketInterface) => {
            socket.chatRooms = [];

            socket.on('login', (options: any) => {
                console.log(options);
            });

            socket.on('logout', (options: any) => {
                console.log(options);
            });

            createChatSocketEventHandler(socket);
            createChatRoomSocketEventHandler(socket);
        });
}
