package com.apobates.forum.thrones.controller.helper;

import com.apobates.forum.core.entity.proxy.TopicReplica;
import com.apobates.forum.core.service.TopicService;
import com.apobates.forum.thrones.vo.ForumThreads;
import com.apobates.forum.utils.Commons;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * 最新的话题推送
 *
 * @author xiaofanku
 * @since 20200527
 */
public class TopicSocketUpdatedHandler extends TextWebSocketHandler {
    @Autowired
    private TopicService topicService;
    private final static Logger logger = LoggerFactory.getLogger(TopicSocketUpdatedHandler.class);
    
    //周期性的?步进式的
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        String cmdMsg = message.getPayload();
        logger.info("[TopicUpdated]sock.js cmd: " + cmdMsg);
        
        String responseData = null;
        Map<String, Long> jsonData = Commons.fromStatsString(cmdMsg);
        long cmdSybol = 0;
        try {
            cmdSybol = jsonData.get("cmd");
        } catch (NullPointerException e) {
        }
        //{"id":"boardId", "ux":"previousUx","cmd":"topic_list"}
        if (cmdSybol == 1) { //推消息
            responseData = boardUpdatedTopic(jsonData.get("id"), jsonData.get("ux").intValue());
        }
        if (cmdSybol == 2) { //推消息数量
            long unknown = topicService.getRecentByUnixStampSize(jsonData.get("id"), jsonData.get("ux").intValue());
            Map<String,String> data = Map.of("id", jsonData.get("id")+"", "ux", jsonData.get("ux")+"", "size", unknown+"");
            responseData = Commons.toJson(data);
        }
        //
        if (null == responseData) {
            return;
        }
        //
        String id = session.getId();
        try {
            session.sendMessage(new TextMessage(responseData));
        } catch (IOException e) {
            logger.info("[TopicUpdated]session id: " + id + ", exception: " + e.getMessage());
        }
    }
    
    // 版块最新的话题
    private String boardUpdatedTopic(long boardId, int previousUx) {
        List<TopicReplica> rs = topicService.getRecentByUnixStamp(boardId, previousUx);
        if (null == rs || rs.isEmpty()) {
            return null;
        }
        List<ForumThreads> data = rs.stream().map(ForumThreads::new).collect(Collectors.toList());
        return new Gson().toJson(data);
    }
}