package _VisualDVM.ComponentsServer.Component.Sapfor;
import Common.MainModule_;
import Common.Utils.Utils_;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class MessagesServer {
    ServerSocket serverSocket = null;
    Socket client = null;
    Thread thread = null;
    private int port;
    public MessagesServer() throws Exception {
        serverSocket = new ServerSocket(0, 5, InetAddress.getLoopbackAddress());
        setPort(serverSocket.getLocalPort());
    }
    public MessagesServer(int port_in) {
        port = port_in;
    }
    public void Start() {
        thread = new Thread(() -> {
            while (true) {
                try {
                    client = serverSocket.accept();
                    BufferedReader in = new BufferedReader(new
                            InputStreamReader(client.getInputStream()));
                    String line;
                    while ((line = in.readLine()) != null) {
                        if (MainModule_.instance.getUI().HasPassForm())
                            MainModule_.instance.getUI().GetPassForm().Result.ShowSapforMessage(line);
                    }
                } catch (Exception ex) {
                    //  UI.Print(DebugPrintLevel.MessagesServer, "соединение сброшено!");
                }
            }
        });
        thread.start();
    }
    public void Shutdown() {
        try {
            if (client != null) {
                client.setSoLinger(true, 500);
                client.close();
            }
            if (serverSocket != null)
                serverSocket.close();
        } catch (Exception e) {
            Utils_.MainLog.PrintException(e);
        }
    }
    public int getPort() {
        return port;
    }
    public void setPort(int port) {
        this.port = port;
    }
}
