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

import cn.reghao.jutil.jdk.serializer.JsonConverter;
import cn.reghao.tnb.auth.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.chat.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 java.io.IOException;

/**
 * @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 ChatConnection chatConnection;

    public ChatService(ChatConnection chatConnection) {
        this.chatConnection = chatConnection;
    }

    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 = chatConnection.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 (chatConnection.getUserSession(receiverId) == null) {
            // wsConnection.broadcastCluster(payload);
            return;
        }
        chatConnection.sendChatMessage(receiverId+"", chatPayload);
    }
}
