package _VisualDVM.Passes.All;
import Common.Passes.PassException;
import Common.Visual.Windows.ReadOnlyMultilineTextForm;
import _VisualDVM.GlobalData.RemoteFile.RemoteFile;
import _VisualDVM.Passes.Server.TestingServerPass;
import _VisualDVM.Repository.Server.ServerCode;
import _VisualDVM.Utils;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.List;
import java.util.Vector;
public class ShowTestingServerFile extends TestingServerPass<RemoteFile> {
    String title;
    File localFile;
    @Override
    protected boolean isSafe() {
        return false;
    }
    @Override
    protected boolean canStart(Object... args) throws Exception {
        title = (String) args[0];
        target = (RemoteFile) args[1];
        return SendRequest(ServerCode.ReceiveFile, target.full_name);
    }
    @Override
    protected void body() throws Exception {
        localFile = Utils.getTempFileName(target.name);
        if (request.server_response != null)
            request.server_response.Unpack(localFile);
        else throw new PassException("Файл не найден");
    }
    @Override
    protected boolean validate() {
        return localFile.exists();
    }
    @Override
    protected void showDone() throws Exception {
        ReadOnlyMultilineTextForm ff = new ReadOnlyMultilineTextForm();
        List<String> lines = FileUtils.readLines(localFile);
        Vector<String> res = new Vector<>();
        for (int i = lines.size() - 1; i >= 0; i--)
            res.add(lines.get(i));
        ff.ShowDialog(title,
                String.join("\n", res)
        );
    }
}
