package net.tccn.redim;

import net.tccn.bbs.user.UserService;
import net.tccn.redim.entity.MsgRecord;
import net.tccn.redim.info.MsgInfo;
import net.tccn.redim.service.ImFriendService;
import net.tccn.redim.service.ImMsgService;
import org.redkale.net.http.*;
import org.redkale.service.RetResult;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CompletableFuture;

/**
 * Created by liangxianyou at 2018/7/8 22:51.
 */
@RestWebSocket(name = "chat", catalog = "ws", comment = "文字聊天", anyuser = true)
public class ChatWebSocket extends WebSocket {

    @Resource
    protected ImMsgService chatService;
    @Resource
    protected ImFriendService imFriendService;

    @Resource
    protected UserService userService;

    protected Random random = new Random();

    @Override
    protected CompletableFuture<String> onOpen(HttpRequest request) {
        String token = request.getParameter("token");
        return CompletableFuture.supplyAsync(() -> {
            if (token == null) {
                setAttribute("isyk", true);
                return request.getSessionid(false);
            }
            return token;
        });
    }

    @Override
    public CompletableFuture createUserid() {
        return CompletableFuture.supplyAsync(() -> {
            int userid = 0;

            //fixme: 1、isyk => tour;    2、set cate to user global
            if (getAttribute("isyk") == null) {//tour
                userid = userService.currentUserid(getSessionid());
                setAttribute("isyk", true);
            }

            //如果未获取登录信息，使用token.hashCode 负值 作为登录用户
            if (userid == 0) {
                //MsgInfo msgInfo = new MsgInfo();
                userid = -Math.abs(getSessionid().hashCode());
            }

            //接收离线信息
            int finalUserid = userid;
            CompletableFuture.runAsync(() -> {
                RetResult<List<MsgRecord>> list = chatService.offlineMsg(finalUserid);
                List<net.tccn.redim.entity.MsgRecord> recordList = list.getResult();

                if (recordList != null && recordList.size() > 0) {
                    recordList.forEach(msgRecord -> {
                        RetResult<MsgInfo> msgInfo = chatService.createMsgInfo(msgRecord);
                        send(msgInfo.getResult()).thenAccept(x -> {
                            if ((Integer) x == 0) {//发送成功
                                msgRecord.setStatus((short) 20);
                            }
                            chatService.update(msgRecord);
                        });
                    });
                }
            });

            return userid;
        });
    }

    @Override
    public void preOnMessage(String restmapping, WebSocketParam param, Runnable messageEvent) {
        super.preOnMessage(restmapping, param, messageEvent);
    }

    @RestOnMessage(name = "text")
    public void onChatMessage(MsgRecord msg, Map<String, String> extmap) {
        msg.setFromuserid((Integer) getUserid());

        RetResult<MsgInfo> msgInfo = chatService.createMsgInfo(msg);

        sendMessage(msgInfo.getResult(), msg.getTouserid()).thenAccept(x -> {
            if ((Integer) x == 0) {//发送成功
                msg.setStatus((short) 20);
            }
            chatService.insert(msg);
        });
    }



    /*@RestOnMessage(name = "close")
    public void onClose(int code, String reason) {
        System.out.println("close!");
        super.onClose(code, reason);
    }*/
}