package cn.reghao.tnb.message.app.ws.service;

import cn.reghao.jutil.jdk.serializer.JsonConverter;
import cn.reghao.tnb.account.api.iface.AccountQuery;
import cn.reghao.tnb.message.api.model.EventType;
import cn.reghao.tnb.message.api.model.resp.EventMessageResp;
import cn.reghao.tnb.message.api.model.resp.EvtLoginResp;
import cn.reghao.tnb.message.app.ws.WsConnection;
import cn.reghao.tnb.message.app.ws.msg.ChatPayload;
import cn.reghao.tnb.user.api.iface.UserContactService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.List;

/**
 * @author reghao
 * @date 2022-04-21 10:32:37
 */
@Slf4j
@Component
public class ChatService {
    @DubboReference(check = false, retries = 0)
    private AccountQuery accountQuery;
    @DubboReference(check = false, retries = 0)
    private UserContactService userContactService;

    private final WsConnection wsConnection;

    public ChatService(WsConnection wsConnection) {
        this.wsConnection = wsConnection;
    }

    public void onLoginEvent(long userId, boolean online) {
        EvtLoginResp evtLoginResp = new EvtLoginResp(userId, online);
        EventMessageResp<EvtLoginResp> resp = new EventMessageResp<>(EventType.event_login, evtLoginResp);
        TextMessage textMessage = new TextMessage(JsonConverter.objectToJson(resp));

        userContactService.setOnline(userId, online);
        List<Long> friendIds = userContactService.getOnlineFriends(userId);
        for (Long friendId : friendIds) {
            WebSocketSession session = wsConnection.getUserSession(friendId);
            if (session != null) {
                try {
                    session.sendMessage(textMessage);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void onEventTalk(String payload) throws IOException {
        ChatPayload chatPayload = JsonConverter.jsonToObject(payload, ChatPayload.class);
        long receiverId = chatPayload.getReceiverId();
        if (wsConnection.getUserSession(receiverId) == null) {
            wsConnection.clusterBroadcast(payload);
            return;
        }

        wsConnection.sendChatMessage(receiverId+"", chatPayload);
    }
}
