package org.aohe.web;

import org.aohe.constant.SocketEnum;

import java.net.UnknownHostException;
import java.util.HashMap;

public class SocketUtils {

    private static final HashMap<String, SocketServer> map = new HashMap<>();

    public SocketUtils() throws Exception {
    }

    public static SocketServer get(String name ) {
        return map.get(name);
    }

    public static void start(String name ,int port) {
        try {
            SocketServer server = new SocketServer(port);
            server.start();
            map.put(name, server);
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
    }

    public static void start(SocketEnum socketEnum) {
        try {
            SocketServer server = get(socketEnum.getName());
            if(server != null){
                //不为空 则先关闭再启动
                safeStop(socketEnum);
            }
            if(SocketEnum.CAM_SOCKET.equals(socketEnum)){
                server = new CamSocketServer(socketEnum.getPort());
            }else{
                server = new SocketServer(socketEnum.getPort());
            }
            server.start();
            map.put(socketEnum.getName(), server);
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
    }

    public static void safeStop(String name) {
        SocketServer server = map.get(name);
        if(server != null){
            try {
                server.stop(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void safeStop(SocketEnum socketEnum) {
        SocketServer server = map.get(socketEnum.getName());
        if(server != null){
            try {
                server.stop(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
    public static void safeStopAll(){
        map.forEach((k,v)-> safeStop(k));
    }

}
