package Visual_DVM_2021.Passes.All;
import Common.Current_;
import Common.Utils.Utils_;
import _VisualDVM.Current;
import Common.Visual.Windows.Dialog.Text.ReadOnlyMultilineTextForm;
import _VisualDVM.Global;
import _VisualDVM.Utils;
import _VisualDVM.Repository.Component.Component;
import _VisualDVM.Repository.Server.ServerCode;
import _VisualDVM.Repository.Server.ServerExchangeUnit_2021;
import Visual_DVM_2021.Passes.Server.ComponentsRepositoryPass;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.List;
import java.util.Vector;
public class ShowComponentChangesLog extends ComponentsRepositoryPass<Component> {
    @Override
    public String getIconPath() {
        return "/icons/Log.png";
    }
    @Override
    public String getButtonText() {
        return "";
    }
    File res;
    @Override
    protected boolean canStart(Object... args) throws Exception {
        if (Global.mainModule.Check(Log, Current.Component)) {
            target = Global.mainModule.getComponent();
            return true;
        }
        return false;
    }
    @Override
    protected void performPreparation() throws Exception {
        res = Utils.getTempFileName("component_changes");
    }
    @Override
    protected void ServerAction() throws Exception {
        Command(new ServerExchangeUnit_2021(ServerCode.GetComponentChangesLog, target.getComponentType().toString()));
        Utils_.bytesToFile((byte[]) response.object, res);
    }
    @Override
    protected boolean validate() {
        return res.exists();
    }
    @Override
    protected void showDone() throws Exception {
        ReadOnlyMultilineTextForm ff = new ReadOnlyMultilineTextForm();
        List<String> lines = FileUtils.readLines(res);
        Vector<String> res = new Vector<>();
        for (int i = lines.size() - 1; i >= 0; i--)
            res.add(lines.get(i));
        ff.ShowDialog("Журнал изменений компонента " +
                        Utils_.Brackets(target.getComponentType().getDescription()),
                String.join("\n", res)
        );
    }
}
