package _VisualDVM.Passes.Server;
import Common.Database.Objects.DBObject;
import Common.Passes.Pass;
import Common.Passes.PassException;
import Common.Utils.Utils_;
import _VisualDVM.Global;
import _VisualDVM.Repository.RepositoryRefuseException;
import _VisualDVM.Repository.RepositoryServer;
import _VisualDVM.Repository.Server.ServerCode;
import _VisualDVM.Repository.Server.ServerExchangeUnit_2021;
import _VisualDVM.Utils;
import javafx.util.Pair;

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<T> {
    protected S server;
    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;
    public RepositoryPass(S server_in) {
        server = server_in;
    }
    @Override
    protected boolean needsAnimation() {
        return true;
    }
    protected int getTimeout() {
        return Global.properties.SocketTimeout;
    }
    //-
    protected void connect() throws Exception {
        clientSocket = Utils.createClientSocket(InetAddress.getByName(Global.properties.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 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_.fileToBytes(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);
    }
    public void EditObject(DBObject object) throws Exception {
        Command(new ServerExchangeUnit_2021(ServerCode.EditObject, "", object));
    }
    //-
    public void DeleteObject(DBObject object) throws Exception {
        Command(new ServerExchangeUnit_2021(ServerCode.DeleteObjectByPK, "",
                new Pair<>(object.getClass(), object.getPK())));
    }
}
