package GlobalData.RemoteFile.UI;
import Common.Current;
import Common.Global;
import Common.UI.UI;
import Common.UI.Windows.Dialog.Dialog;
import GlobalData.RemoteFile.RemoteFile;
import files.ConnectionPass;
import com.jcraft.jsch.ChannelSftp.LsEntry;

import javax.swing.tree.DefaultMutableTreeNode;
import java.util.Collections;
import java.util.Comparator;
import java.util.Vector;
public class RemoteFileChooser extends Dialog<String, RemoteFileChooserFields> {
    public DefaultMutableTreeNode root = new DefaultMutableTreeNode("нет данных");
    ConnectionPass session;
    RemoteFile root_file;
    boolean target_is_directory = false;
    public RemoteFileChooser() {
        super(RemoteFileChooserFields.class);
    }
    @Override
    public boolean NeedsScroll() {
        return false;
    }
    @Override
    public void Init(Object... params) {
        session = (ConnectionPass) params[0];
        target_is_directory = (boolean) params[1];
        try {
            Refresh(session.getSftpChannel().pwd());
        } catch (Exception ex) {
            Global.Log.PrintException(ex);
            onCancel(); //закрываем окно.
        }
    }
    public void ShowCurrentRemoteFile() {
        fields.lCurrentFile.setText(Current.getRemoteFile().full_name);
    }
    public void Refresh(String path) {
        try {
            Current.set(Current.RemoteFile, null);//сброс текущего файла перед любым обновлением.
            fields.lCurrentFile.setText("?");
            //-------------------------------------------------------------------
            root_file = new RemoteFile(path, true);
            root = new DefaultMutableTreeNode(root_file);
            //-------------------------------------------------------
            Vector<LsEntry> files = session.getSftpChannel().ls(path);
            Vector<RemoteFile> directories_ = new Vector<>();
            Vector<RemoteFile> files_ = new Vector<>();
            //отсортировать по принадлежности.
            for (LsEntry file : files) {
                if (!file.getFilename().equals(".") && !file.getFilename().equals("")) {
                    if (file.getAttrs().isDir())
                        directories_.add(new RemoteFile(root_file.full_name, file.getFilename(), true));
                    else
                        files_.add(new RemoteFile(root_file.full_name, file.getFilename(), false));
                }
            }
            //отсортировать по алфавиту
            Collections.sort(directories_, Comparator.comparing(o -> o.name));
            Collections.sort(files_, Comparator.comparing(o -> o.name));
            for (RemoteFile f : directories_)
                root.add(new DefaultMutableTreeNode(f));
            for (RemoteFile f : files_)
                root.add(new DefaultMutableTreeNode(f));
            //просто пересоздаем дерево
            fields.treeForm.Show();
            fields.lCurrentFolder.setText(path);
        } catch (Exception ex) {
            Global.Log.PrintException(ex);
            onCancel();
        }
    }
    public void goHome() {
        try {
            Refresh(session.getSftpChannel().getHome());
        } catch (Exception ex) {
            Global.Log.PrintException(ex);
            onCancel(); //закрываем окно.
        }
    }
    public void goUp() {
        if (!root_file.full_name.equals("/")) {
            Refresh(root_file.parent);
        } else UI.Info("Корневая папка файловой системы достигнута.");
    }
    @Override
    public void validateFields() {
        String target_name = target_is_directory ? "папка" : "файл";
        if (Current.HasRemoteFile()) {
            if (target_is_directory != Current.getRemoteFile().isDirectory)
                Log.Writeln("Выбранный объект - не " + target_name);
        } else Log.Writeln(target_name + " не выбран(а)");
    }
}
