package _VisualDVM.Repository.Server;
import Common.Passes.PassException;
import Common.Utils.Utils_;
import _VisualDVM.Passes.Server.RepositoryPass;

import java.io.FileWriter;
import java.io.Serializable;
import java.util.Date;
public abstract class RepositoryServerClient<T extends RepositoryServer> {
    protected abstract T getServer();
    protected int getSleepMillis() {
        return 2000;
    }
    //---
    protected boolean isPrintOn() {
        return true;
    }
    protected void Print(String message) {
        try {
            if (isPrintOn()) {
                FileWriter testLog = new FileWriter(getClass().getSimpleName() + "_Log.txt", true);
                String dmessage = Utils_.Brackets(new Date()) + " " + message;
                testLog.write(dmessage + "\n");
                testLog.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    //--
    protected Object ServerCommand(ServerCode code_in, String arg, Serializable object_in) throws Exception {
        RepositoryPass<T, Object> pass = new RepositoryPass<T, Object>(getServer()) {
            @Override
            public String getDescription() {
                return "";
            }
            @Override
            protected void ServerAction() throws Exception {
                Command(new SafeServerExchangeUnit(code_in, arg, object_in));
                target = server_response.object;
            }
            @Override
            protected boolean validate() {
                return Log.isEmpty();
            }
            @Override
            protected int getTimeout() {
                return 0;
            }
        };
        if (!pass.Do()) {
            ServerConnectionError(code_in, pass.Log.toString());
        }
        return pass.target;
    }
    protected Object ServerCommand(ServerCode code_in, Serializable object_in) throws Exception {
        return ServerCommand(code_in, "", object_in);
    }
    protected Object ServerCommand(ServerCode code_in) throws Exception {
        return ServerCommand(code_in, "", null);
    }
    protected void ServerConnectionError(ServerCode code_in, String logText) throws Exception {
        throw new PassException(Utils_.Brackets(new Date().toString()) + " Ошибка взаимодействия с сервером " + code_in);
    }
    protected abstract void perform() throws Exception;
    public void Perform() {
        try {
            perform();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            Utils_.sleep(getSleepMillis());
        }
    }
}
