package com.yeejoin.precontrol.common.ws;

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

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import lombok.Data;
import lombok.NoArgsConstructor;

@ServerEndpoint("/ws/picture/{username}")
@Data
@NoArgsConstructor
@Component
public class WebSocketPicture {

	private static int onlineCount = 0;

	private static Map<String, WebSocketPicture> clients = new ConcurrentHashMap<String, WebSocketPicture>();

	private Session session;

	private String username;

	@OnOpen
	public void onOpen(@PathParam(value = "username") String username, Session session) throws IOException {

		this.username = username;

		this.session = session;

		addOnlineCount();

		clients.put(username, this);

		System.out.println("已连接");
		
	}

	@OnClose
	public void onClose() throws IOException {

		clients.remove(username);

		subOnlineCount();

	}

	@OnMessage
	public void onMessage(String message) throws IOException {

		JSONObject jsonTo = JSONObject.parseObject(message);

		System.out.println(jsonTo);
//        String mes = (String) jsonTo.get("message");

//        if (!jsonTo.get("To").equals("All")){ 
//
//            sendMessageTo(mes, jsonTo.get("To").toString()); 
//
//        }else{ 
//
//            sendMessageAll("给所有人"); 
//
//        } 

	}

	@OnError
	public void onError(Session session, Throwable error) {

		error.printStackTrace();

	}

	public void sendMessageTo(String message, String To) throws IOException {

		// session.getBasicRemote().sendText(message);

		// session.getAsyncRemote().sendText(message);

		for (WebSocketPicture item : clients.values()) {

			if (item.username.equals(To))

				item.session.getAsyncRemote().sendText(message);

		}

	}

	public static synchronized void sendMessageAll(String message) {

		for (WebSocketPicture item : clients.values()) {
			item.session.getAsyncRemote().sendText(message);
		}

	}

	public static synchronized int getOnlineCount() {

		return onlineCount;

	}

	public static synchronized void addOnlineCount() {

		WebSocketPicture.onlineCount++;

	}

	public static synchronized void subOnlineCount() {

		WebSocketPicture.onlineCount--;

	}

	public static synchronized Map<String, WebSocketPicture> getClients() {

		return clients;

	}

}