package _VisualDVM.Passes.All;
import _VisualDVM.GlobalData.Machine.Machine;
import _VisualDVM.GlobalData.RemoteFile.RemoteFile;
import _VisualDVM.GlobalData.User.User;
import _VisualDVM.Passes.SSH.ConnectionPass;
import com.jcraft.jsch.ChannelSftp;

import java.io.File;
import java.util.Comparator;
import java.util.Vector;
public class ArchivesBackupPass extends ConnectionPass<File> {
    File src;
    @Override
    protected boolean canStart(Object... args) throws Exception {
        machine = (Machine) args[0];
        user = (User) args[1];
        src = (File) args[2];
        return true;
    }
    @Override
    public String getDescription() {
        return "Создание резервной копии базы данных на машине";
    }
    @Override
    protected void ServerAction() throws Exception {
        RemoteFile workspace = new RemoteFile(user.connection.sftpChannel.getHome(), "_sapfor_x64_backups", true);
        user.connection.MKDIR(workspace);
        RemoteFile dst = new RemoteFile(workspace.full_name, src.getName());
        user.connection.putSingleFile(src, dst);
        //-теперь, удалить старые файлы.
        Vector<ChannelSftp.LsEntry> raw_files = user.connection.sftpChannel.ls(workspace.full_name);
        Vector<RemoteFile> files = new Vector<>();
        for (ChannelSftp.LsEntry file : raw_files) {
            if (!file.getAttrs().isDir()) {
                RemoteFile rfile = new RemoteFile(workspace.full_name, file.getFilename(), false);
                rfile.updateTime = RemoteFile.convertUpdateTime(file.getAttrs().getMTime());
                files.add(rfile);
            }
        }
        //сортируем по времени обновления. по убыванию.
        files.sort(new Comparator<RemoteFile>() {
                    @Override
                    public int compare(RemoteFile o1, RemoteFile o2) {
                        return Long.compare(o1.updateTime, o2.updateTime);
                    }
                }.reversed()
        );
        for (int i = 2; i < files.size(); ++i) {
            user.connection.sftpChannel.rm(files.get(i).full_name);
        }
        //--------------
    }
}
