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

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
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;
import com.apobates.forum.core.api.service.PostsService;
import com.apobates.forum.core.api.service.TopicService;
import com.apobates.forum.core.entity.Posts;
import com.apobates.forum.core.entity.Topic;
import com.apobates.forum.trident.vo.ForumThreads;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
 * 最新的话题推送
 * 
 * @author xiaofanku
 * @since 20190416
 */
public class TopicUpdatedHandler extends TextWebSocketHandler{
	@Autowired
	private TopicService topicService;
	@Autowired
	private PostsService postsService;
	private final static Logger logger = LoggerFactory.getLogger(TopicUpdatedHandler.class);
	
	//周期性的?步进式的
	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) {
		//{"id":"boardId", "ux":"previousUx","cmd":"topic_list"}//1
		//{"id":"topicId", "ux":"previousUx","cmd":"posts_list"}//2
		String cmdMsg = message.getPayload();
		logger.info("[TopicUpdated]sock.js cmd: " + cmdMsg);
		
		String responseData = null;
		Map<String,Long> jsonData = new Gson().fromJson(cmdMsg, new TypeToken<HashMap<String, Long>>() { }.getType());
		long cmdSybol = 0;
		try {
			cmdSybol = jsonData.get("cmd");
		}catch(NullPointerException e) {}
		
		if(cmdSybol == 1) {
			responseData = boardUpdatedTopic(jsonData.get("id"), jsonData.get("ux").intValue());
		}
		if(cmdSybol == 2) {
			responseData = topicUpdatedPostes(jsonData.get("id"), jsonData.get("ux").intValue());
		}
		//
		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<Topic> 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);
	}
	
	// 话题最近的回复
	private String topicUpdatedPostes(long topicId, int previousUx) {
		Stream<Posts> rs = postsService.getRecentByUnixStamp(topicId, previousUx);
		//处理内容
		if(rs.count()==0) {
			return null;
		}
		return new Gson().toJson(rs.collect(Collectors.toList()));
	}
}
