package electrosphere.net.server;

import electrosphere.main.Main;
import electrosphere.net.NetUtils;
import electrosphere.net.parser.net.message.NetworkMessage;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author amaterasu
 */
public class Server implements Runnable{
    
    int port;
    
    ServerSocket serverSocket;
    
    HashMap<String,ServerConnectionHandler> clientMap;
    
    
    
    
    void initServer(){
        clientMap = new HashMap();
    }
    
    
    public Server(int port){
        this.port = port;
    }

    @Override
    public void run() {
        initServer();
        try {
            serverSocket = new ServerSocket(port);
        } catch (IOException ex) {
            System.err.println("Failed to start server socket!");
            ex.printStackTrace();
            System.exit(1);
        }
        while(Main.isRunning()){
            Socket newSocket;
            try {
                newSocket = serverSocket.accept();
                ServerConnectionHandler newClient = new ServerConnectionHandler(newSocket);
                clientMap.put(newSocket.getInetAddress().getHostAddress(), newClient);
                new Thread(newClient).start();
            } catch (IOException ex) {
                System.err.println("Socket error on client socket!");
            }
        }
    }
    
    public void close(){
        try {
            serverSocket.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    
    public void broadcastMessage(NetworkMessage message){
        for(ServerConnectionHandler client : clientMap.values()){
            if(client.playerID != Main.playerId){
                client.addMessagetoOutgoingQueue(message);
            }
        }
    }
}
