import {createSlice} from "@reduxjs/toolkit";
import {APP_SERVER} from "@constants/app";
import CSClientWrap from "@features/colyseus/CSClientWrap";

export const Socket=createSlice({
    name: 'socket',
    initialState: {
        clients:{}
    },
    reducers: {
        onConnect:(state, action) => {
            let roomName=action.payload;
            if (roomName!=null){
                state.clients[roomName]={
                    isConnected:true,
                    message:{}//最后一条消息
                }
            }
        },
        onDisconnect:(state, action) =>{
            let roomName=action.payload;
            let client=state.clients[roomName];
            if (client!=null){
                client.isConnected=false;
            }
        },
        onSend:(state, action) =>{

        },
        onMessage:(state, action) => {
            let {roomName,type,message}=action.payload;
            let client=state.clients[roomName];
            if (client!=null){
                client.message={type,message};
            }
        }
    },
    extraReducers: (builder) => {
    },
})
export const {onConnect,onDisconnect,onSend,onMessage} = Socket.actions;
export const getHallConnState=(state)=>{
    let isConnected=false;
    let clients=state.socket.clients;
    if (clients!=null){
        let hall=clients[APP_SERVER.ROOM_HALL];
        if (hall!=null)return hall.isConnected;
    }
    return isConnected;
}
export default Socket.reducer;

export const connectServer=({roomName, serverUrl,messageCB=null,onRoomConnect=null,onRoomTimeoutClose=null,options={}})=>{
    return async (dispatch, getState) => {
        if (CSClientWrap.isConnected(roomName))return ;
        let isConnected=await CSClientWrap.connect(roomName,serverUrl,(type,message)=>{
            dispatch(onMessage({roomName,type,message}));
            if (messageCB!=null)dispatch(messageCB(type,message));
        },(connected)=>{
            dispatch(onConnect(roomName));
            if (onRoomConnect!=null)dispatch(onRoomConnect());
        },()=>{
            dispatch(onDisconnect(roomName));
            if (onRoomTimeoutClose!=null)dispatch(onRoomTimeoutClose());
        });
    }
}
export const disconnectServer=(roomName)=>{
    return async (dispatch, getState) => {
        await CSClientWrap.disconnect(roomName);
        dispatch(onDisconnect(roomName));
    }
}
export const sendToServer=({roomName,type,message=""})=>{
    return (dispatch)=>{
        CSClientWrap.send(roomName,type,message);
        dispatch(onSend({roomName,type,message}));
    }
}
// export const connectHall=()=>{
//     return connectServer({
//         roomName:APP_SERVER.ROOM_HALL,
//         serverUrl:APP_SERVER.SERVER_URL
//     });
// }
