package Visual_DVM_2021.Passes.All;
import Common.Global;
import Common.Utils.Utils;
import GlobalData.Machine.Machine;
import GlobalData.RemoteFile.RemoteFile;
import GlobalData.User.User;
import Visual_DVM_2021.Passes.SSH.ConnectionPass;
import com.jcraft.jsch.ChannelSftp;

import java.io.File;
import java.nio.file.Paths;
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
    protected boolean needsInitialize() {
        return false;
    }
    @Override
    protected void ServerAction() throws Exception {
        String workspace_path = Utils.toU(Paths.get(sftpChannel.getHome(),Global.properties.BackupWorkspace).toString());
        RemoteFile workspace = new RemoteFile(workspace_path, true);
        tryMKDir(workspace);
        RemoteFile dst = new RemoteFile(workspace.full_name, src.getName());
        putSingleFile(src, dst);
        //-теперь, удалить старые файлы.
        Vector<ChannelSftp.LsEntry> raw_files = 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((o1, o2) -> (int) (o2.updateTime - o1.updateTime));
        for (int i = 2; i < files.size(); ++i) {
            System.out.println(files.get(i).full_name + ":" + files.get(i).updateTime);
            sftpChannel.rm(files.get(i).full_name);
        }
        //--------------
    }
}
