package com.yeejoin.precontrol.common.ws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.precontrol.common.component.SpringContextHolder;
import com.yeejoin.precontrol.common.dto.MessageDto;
import com.yeejoin.precontrol.common.service.IVideoBlockService;
import com.yeejoin.precontrol.common.service.impl.VideoBlockServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: songLei
 * @Description:
 * @Date: 2021/10/18 16:10
 * @Version: 1.0
 */
@Slf4j
@ServerEndpoint(value = "/videoBlockSocket/{personId}")
@Component
public class WebSocketVideoBlock {
	/** 记录当前在线连接数 */
	private static AtomicInteger onlineCount = new AtomicInteger(0);

	/** 存放所有在线的客户端 */
	private static Map<Long, Session> clients = new ConcurrentHashMap<>();

	/**
	 * 连接建立成功调用的方法
	 */
	@OnOpen
	public void onOpen(@PathParam(value = "personId") Long personId, Session session) {
		onlineCount.incrementAndGet(); // 在线数加1
		clients.put(personId, session);
		IVideoBlockService iVideoBlockService = SpringContextHolder.getBean(IVideoBlockService.class);
		iVideoBlockService.browseVideo(personId);
		log.info("有新连接加入：{}，当前在线人数为：{}，当前用户ID：{}", session.getId(), onlineCount.get(), personId);
	}

	/**
	 * 连接关闭调用的方法
	 */
	@OnClose
	public void onClose(Session session) {
		onlineCount.decrementAndGet(); // 在线数减1
		if (clients.containsValue(session)) {
			Long personId = null;
			for (Long getKey : clients.keySet()) {
				if (clients.get(getKey).equals(session)) {
					personId = getKey;
				}
			}
			clients.remove(personId);
			IVideoBlockService iVideoBlockService = SpringContextHolder.getBean(IVideoBlockService.class);
			iVideoBlockService.leaveBrowse(personId);
		}
		log.info("有一连接关闭：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
	}

	/**
	 * 收到客户端消息后调用的方法
	 * 
	 * @param message 客户端发送过来的消息
	 */
	@OnMessage
	public void onMessage(String message, Session session) {
		log.info("服务端收到客户端[{}]的消息[{}]", session.getId(), message);
		try {
			MessageDto messageDto = JSON.parseObject(message, MessageDto.class);
			VideoBlockServiceImpl service = SpringContextHolder.getBean(VideoBlockServiceImpl.class);
			service.restBrowsingVideo(messageDto.getPersonId());
			if (messageDto != null) {
				Session toSession = clients.get(messageDto.getPersonId());
				if (toSession != null) {
					sendMessage(message, toSession);
				}
			}
		} catch (Exception e) {
			log.error("解析失败：{}", e);
		}
	}

	@OnError
	public void onError(Session session, Throwable error) {
		log.error("发生错误");
		error.printStackTrace();
	}

	/**
	 * 服务端发送消息给客户端
	 */
	private static void sendMessage(String message, Session toSession) {
		try {
			log.info("服务端给客户端[{}]发送消息[{}]", toSession.getId(), message);
			toSession.getBasicRemote().sendText(message);
		} catch (Exception e) {
			log.error("服务端发送消息给客户端失败：{}", e);
		}
	}

	public static void stop(Long personId) {
		MessageDto messageDto = new MessageDto();
		messageDto.setPersonId(personId);
		messageDto.setMessage("stop");
		Session toSession = clients.get(personId);
		try {
			toSession.getBasicRemote().sendText(JSONObject.toJSONString(messageDto));
			clients.remove(personId);
			IVideoBlockService iVideoBlockService = SpringContextHolder.getBean(IVideoBlockService.class);
			iVideoBlockService.leaveBrowse(personId);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
