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 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.letterbox.api.service.InboxService;
import com.apobates.forum.trident.digest.MessageBodyDigest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
 * 消息推送
 * @author xiaofanku
 * @since 20190704
 */
public class MessagePushHandler extends TextWebSocketHandler{
	@Autowired
	private InboxService inboxService;
	private final static Logger logger = LoggerFactory.getLogger(MessagePushHandler.class);
	
	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) {
		//{"id":"memberId", "ux":"previousUx","cmd":"unread_size"} //1未读的消息数量
		//{"id":"memberId", "sender":"消息的发送方", "ux":"previousUx","cmd":"body_list"} //2消息内容页
		
		String cmdMsg = message.getPayload();
		logger.info("[MessagePushHandler]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 = updateUnReadMessages(jsonData.get("id"), jsonData.get("ux").intValue());
		}
		if(cmdSybol == 2) {
			responseData = updateMessageBody(jsonData.get("id"), jsonData.get("sender"), jsonData.get("ux").intValue());
		}
		//
		if (responseData == null) {
			return;
		}
		//
		String id = session.getId();
		try {
			session.sendMessage(new TextMessage(responseData));
		} catch (IOException e) {
			logger.info("[MessagePushHandler]session id: " + id + ", exception: " + e.getMessage());
		}
	}
	//未读消息的数量
	private String updateUnReadMessages(long memberId, int previousUx){
		Long size = inboxService.countForMemberMessages(memberId);
		Map<String,Long> data = new HashMap<>();
		data.put("id", memberId);
		data.put("result", size);
		return new Gson().toJson(data);
	}
	//发件人/收件人最近的消息内容
	private String updateMessageBody(long receiver, long sender, int previousUx){
		List<MessageBodyDigest> data = inboxService.get(sender, receiver, previousUx).map(fm -> new MessageBodyDigest(fm, receiver)).collect(Collectors.toList());
		return new Gson().toJson(data);
	}
}
