package _VisualDVM.Passes.Server;
import Common.Database.RepositoryRefuseException;
import Common.Passes.Pass;
import _VisualDVM.Constants;
import _VisualDVM.Repository.Server.RepositoryServer;
import _VisualDVM.Repository.Server.SafeServerExchangeUnit;
import _VisualDVM.Repository.Server.ServerCode;
import _VisualDVM.Repository.Server.ServerExchangeUnit_2021;
import _VisualDVM.Utils;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.*;
public abstract class RepositoryPass<S extends RepositoryServer, T> extends Pass<T> {
    //-
    public ServerExchangeUnit_2021 client_request;
    public ServerExchangeUnit_2021 server_response;
    protected S server;
    protected ObjectInputStream in = null; // поток чтения из сокета
    protected ObjectOutputStream out = null; // поток записи в сокет
    //-
    protected Socket clientSocket = null; //сокет для общения
    protected ServerCode ExitCode = ServerCode.Undefined;
    public RepositoryPass(S server_in) {
        server = server_in;
    }
    @Override
    protected boolean needsAnimation() {
        return true;
    }
    protected int getTimeout() {
        return Constants.SocketTimeout;
    }
    //-
    protected void connect() throws Exception {
        clientSocket = Utils.createClientSocket(InetAddress.getByName(Constants.ServerAddress),
                server.getPort(),
                getTimeout()
        );
        out = new ObjectOutputStream(clientSocket.getOutputStream());
        in = new ObjectInputStream(clientSocket.getInputStream());
    }
    protected void disconnect() throws Exception {
        if (clientSocket != null)
            clientSocket.close();
        if (in != null)
            in.close();
        if (out != null)
            out.close();
        //-
        clientSocket = null;
        in = null;
        out = null;
    }
    protected abstract void ServerAction() throws Exception;
    protected void unsafe_command(ServerExchangeUnit_2021 request_in) throws Exception {
        ExitCode = ServerCode.Undefined;
        client_request = request_in;
        out.writeObject(client_request);
        server_response = (ServerExchangeUnit_2021) in.readObject();
        switch (ExitCode = server_response.getCode()) {
            case FAIL:
                throw (Exception) server_response.object;
            default:
                break;
        }
    }
    protected void Command(SafeServerExchangeUnit request_in) throws Exception {
        unsafe_command(request_in);
    }
    @Override
    protected void body() throws Exception {
        connect();
        ServerAction();
    }
    @Override
    protected void performFinish() throws Exception {
        disconnect();
    }
    @Override
    protected void CheckException(Exception ex) {
        if (ex instanceof RepositoryRefuseException) {
            Log.Writeln_(ex.getMessage());
            return;
        }
        Throwable cause = getCauseRec(ex);
        if ((cause instanceof UnknownHostException)) {
            Log.Writeln_("Репозиторий не найден.\n" +
                    "Проверьте наличие подключения к сети.");
        } else if ((cause instanceof SocketTimeoutException)) {
            Log.Writeln_("Время ожидания подключения к репозиторию истекло.\n" +
                    "Проверьте наличие подключения к сети.");
        } else if ((cause instanceof ConnectException)) {
            if (cause.getMessage().contains("Connection refused: connect"))
                Log.Writeln_("Серверный компонент не активен. Обратитесь к администрации.");
            else Log.Writeln_("Ошибка соединения");
        } else
            super.CheckException(ex);
    }
}
