package Visual_DVM_2021.Passes.All;
import Common.Current;
import Common.Global;
import Common.UI.Menus_2023.PassMenuItem;
import Common.UI.Trees.DataTree;
import Common.UI.Windows.Dialog.Dialog;
import Common.Utils.Utils;
import GlobalData.RemoteFile.RemoteFile;
import Repository.Server.ServerCode;
import Repository.Server.ServerExchangeUnit_2021;
import Visual_DVM_2021.Passes.*;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import java.awt.*;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Vector;
public class ResurrectComponentFromServer extends CurrentComponentPass {
    @Override
    public JMenuItem createMenuItem() {
        if (menuItem == null)
            menuItem = new PassMenuItem(this);
        return menuItem;
    }

    Vector<RemoteFile> backups; //не забывать что файлы на СЕРВЕРЕ.
    RemoteFile remoteFile;
    File localFile;
    @Override
    protected boolean canStart(Object... args) throws Exception {
        remoteFile = null;
        localFile = null;
        if (super.canStart() && passes.get(PassCode_2021.GetComponentsBackupsFromServer).Do()) {
            //1. Получить список бекапов.
            backups = (Vector<RemoteFile>) passes.get(PassCode_2021.GetComponentsBackupsFromServer).target;
            backups.sort((o1, o2) -> o2.name.compareTo(o1.name));
            Dialog d = new Dialog(null) {
                @Override
                public int getDefaultWidth() {
                    return 300;
                }
                @Override
                public int getDefaultHeight() {
                    return 400;
                }
                @Override
                public void CreateContent() {
                    DefaultMutableTreeNode root = new DefaultMutableTreeNode("(скрыть)");
                    for (RemoteFile file : backups) {
                        root.add(new DefaultMutableTreeNode(file));
                    }
                    DataTree tree = new DataTree(root) {
                        {
                            setRootVisible(false);
                            setCellRenderer(new DefaultTreeCellRenderer() {
                                @Override
                                public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
                                    super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
                                    Object o = ((DefaultMutableTreeNode) value).getUserObject();
                                    if (o instanceof RemoteFile){
                                        RemoteFile file = (RemoteFile) o;
                                        setText(file.name);
                                    }
                                    return this;
                                }
                            });
                        }
                        @Override
                        public Current getCurrent() {
                            return Current.ComponentServerBackup;
                        }
                    };
                    content = tree;
                }
            };
            if (d.ShowDialog("Выбор версии для восстановления")&&Current.Check(Log, Current.ComponentServerBackup)){
                remoteFile = Current.getComponentServerBackup();
                return true;
            };
        }
        return false;
    }
    @Override
    protected void body() throws Exception {
      //1. Скачать файл.
        Pass_2021 receivePass = new ComponentsRepositoryPass() {
            @Override
            public String getDescription() {
                return "Скачивание файла с сервера";
            }
            @Override
            protected void ServerAction() throws Exception {
                System.out.println(remoteFile.full_name);
                Command(new ServerExchangeUnit_2021(ServerCode.ReceiveFile, remoteFile.full_name));
                localFile = Utils.getTempFileName(remoteFile.name);
                System.out.println(response.object);
                response.Unpack(localFile);
            }
        };
        if (!receivePass.Do())
            throw  new PassException("Не удалось скачать файл!");
        //------------>>
        Files.copy(localFile.toPath(), target.getNewFile().toPath(), StandardCopyOption.REPLACE_EXISTING);
        target.Update();
    }
    @Override
    protected void performDone() throws Exception {
        target.InitialVersionCheck();
        if (target.CanBeUpdated())
            target.CheckIfNeedsUpdateOrPublish();
    }
    @Override
    protected void showDone() throws Exception {
        Global.RefreshUpdatesStatus();
    }
}
