package Visual_DVM_2021.Passes;
import Common.Global;
import Common.Utils.Utils;
import Repository.RepositoryRefuseException;
import Repository.RepositoryServer;
import Repository.Server.ServerCode;
import Repository.Server.ServerExchangeUnit_2021;

import java.io.File;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.*;

public abstract class RepositoryPass<S extends RepositoryServer, T> extends Pass_2021<T> {
    protected S server;
    public RepositoryPass(S server_in) {
        server = server_in;
    }
    protected ObjectInputStream in = null; // поток чтения из сокета
    protected ObjectOutputStream out = null; // поток записи в сокет
    //-
    protected ServerExchangeUnit_2021 request;
    protected ServerExchangeUnit_2021 response;
    //-
    protected Socket clientSocket = null; //сокет для общения
    protected ServerCode ExitCode = ServerCode.Undefined;
    @Override
    protected boolean needsAnimation() {
        return true;
    }
    protected int getTimeout() {
        return Global.properties.SocketTimeout;
    }
    //-
    protected void connect() throws Exception {
        clientSocket = Utils.createClientSocket(InetAddress.getByName(Global.ServerAddress),
                server.getPort(),
                getTimeout()
        );
        out = new ObjectOutputStream(clientSocket.getOutputStream());
        in = new ObjectInputStream(clientSocket.getInputStream());
    }
    protected void disconnect() throws Exception {
        //System.out.println("разрыв соединения...");
        if (clientSocket != null)
            clientSocket.close();
        if (in != null)
            in.close();
        if (out != null)
            out.close();
        //-
        clientSocket = null;
        in = null;
        out = null;
       // System.out.println("done");
    }
    protected abstract void ServerAction() throws Exception;
    protected void Command(ServerExchangeUnit_2021 request_in) throws Exception {
        ExitCode = ServerCode.Undefined;
        request = request_in;
        out.writeObject(request);
        response = (ServerExchangeUnit_2021) in.readObject();
        switch (ExitCode = response.getCode()) {
            case FAIL:
                throw (Exception) response.object;
            case OLD:
                throw new PassException("Сервер устарел.");
            default:
                break;
        }
    }
    protected void SendFile(File src, String dst) throws Exception {
        Command(new ServerExchangeUnit_2021(ServerCode.SendFile, dst, Utils.packFile(src)));
    }
    protected void ReceiveFile(String src, File dst) throws Exception {
        Command(new ServerExchangeUnit_2021(ServerCode.ReceiveFile, src));
        if (response.object != null)
            response.Unpack(dst);
    }
    protected String ReadFile(String src) throws Exception {
        Command(new ServerExchangeUnit_2021(ServerCode.ReadFile, src));
        return response.object.toString();
    }
    @Override
    protected void body() throws Exception {
        connect();
        ServerAction();
    }
    @Override
    protected void performFinish() throws Exception {
        disconnect();
    }
    @Override
    protected void CheckException(Exception ex) {
        if (ExitCode.equals(ServerCode.OLD)) {
            Log.Writeln_("Текущий сервер устарел. Доступны только обновления компонент!");
            return;
        }
        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);
    }
}
