package cn.edu.whu.boot.message.controller;

import cn.edu.whu.boot.message.bean.ResultMessage;
import cn.edu.whu.boot.message.bean.Team;
import cn.edu.whu.boot.message.bean.Worker;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Li Haoming
 */
@RestController
public class LocationController {

    private final Map<String, Team> teamMap = new ConcurrentHashMap<>();


    @Autowired
    private SimpMessagingTemplate template;

    /**
     * worker 包含 worker name 和 当前位置(position)
     * @param worker
     * @param teamId
     */
    @MessageMapping("/location/join/{teamId}")
    @SendTo("/location-broker/sharing/{teamId}")
    public String sharePosition(Worker worker, @DestinationVariable String teamId) {

        //判断是否是该 team 的第一条记录
        if (null == teamMap.get(teamId)) {

            if (null == worker.getName()) {
                return new ResultMessage<String>(false, "用户名为空，视为非法", 400).toString();
            } else {
                Team team = new Team(teamId, worker);
                teamMap.put(teamId, team);
            }
        } else {
            if (null == worker.getName()) {
                return new ResultMessage<String>(false, "用户名为空，视为非法", 400).toString();
            } else {
                teamMap.get(teamId).getMembers().put(worker.getName(), worker);
            }

        }

        return new ResultMessage<String>(true, "位置点已经上传", 200).toString();
    }


    @Scheduled(fixedDelay=2000)
    public void publishUpdates(){

        JSONArray result = new JSONArray();

        for (Map.Entry entry : teamMap.entrySet()) {
            String teamId = (String) entry.getKey();
            Team team = (Team) entry.getValue();
            if (team.size() != 0) {
                JSONObject temp = new JSONObject(true);
                temp.put("teamId", teamId);
                temp.put("workers", team.teamWorkers());
                result.add(temp);
            }
        }
        template.convertAndSend("/location-broker/sharing/common" , result.toJSONString());
    }

}
