package Visual_DVM_2021.UI.Main;
import Common.Current;
import Common.UI.Label.ShortLabel;
import Common.UI.Menus_2023.VisualiserMenuBar;
import Common.UI.UI;
import Common.Utils.TextLog;
import TestingSystem.SAPFOR.SapforPackage.SapforPackage;
import TestingSystem.SAPFOR.SapforTask.SapforTask;
import TestingSystem.SAPFOR.SapforTasksPackage.UI.SapforTasksPackageTree;
import Visual_DVM_2021.Passes.PassCode_2021;
import Visual_DVM_2021.Passes.Pass_2021;

import javax.swing.*;
import java.util.Comparator;
public class SapforPackagesComparisonForm {
    public boolean comparisonMode = false;
    //-->>
    private JPanel content;
    public JPanel getContent() {
        return content;
    }
    protected JToolBar tools;
    protected JLabel lObjectName;
    private JButton bApplyObject;
    private JButton bPrevious;
    private JButton bNext;
    private JButton bCompare;
    private JButton bClose;
    private JPanel treePanel;
    //-->>
    SapforPackagesComparisonForm this_ = null; //?
    SapforPackagesComparisonForm slave = null;
    SapforPackagesComparisonForm master = null;
    //-->>
    protected SapforPackage object = null;
    //-->>
    protected SapforTasksPackageTree Body;
    public JScrollPane treeScroll = null;
    //--->>
    public boolean isMaster() {
        return slave != null;
    }
    public boolean isSlave() {
        return master != null;
    }
    //--->>
    //неперегружаемые методы
    protected void RemoveObject() {
        object = null;
        showNoObject();
        //--
        if (comparisonMode) {
            comparisonMode = false;
            if (isMaster()) {
                slave.comparisonMode = false;
                slave.object = null;
                slave.showNoObject();
            } else {
                master.comparisonMode = false;
                master.object = null;
                master.showNoObject();
            }
        }
    }
    public void ApplyObject() {
        //---Загрузка
        RemoveObject();
        //---
        TextLog log = new TextLog();
        if (Current.Check(log, Current.SapforPackage)) {
            object = Current.getSapforPackage();
            if (object.isLoaded() || (Pass_2021.passes.get(PassCode_2021.DownloadSapforPackage).Do(object))) {
                showObject();
            }
        } else
            UI.Info(log.toString());
    }
    public void Show() throws Exception {
    }
    public void showNoObject() {
        lObjectName.setText("?");
        lObjectName.setToolTipText("Объект не назначен.");
        showNoTree();
        if (isMaster()) {
            UI.getMainWindow().getTestingWindow().ShowNoSapforPackageVersionEtalon();
        } else {
            UI.getMainWindow().getTestingWindow().ShowNoSapforPackageVersion();
        }
    }
    //---
    public void showCommonTree() {
        //---
        treePanel.add(treeScroll = new JScrollPane(
                Body = new SapforTasksPackageTree(object.package_json.root,
                        isMaster() ? Current.SapforEtalonVersion : Current.SapforVersion
                )));
        treePanel.repaint();
        treePanel.revalidate();
    }
    public void showComparisonTree() {
        treePanel.add(treeScroll = new JScrollPane(
                Body = new SapforTasksPackageTree(object.package_json.comparison_root,
                        isMaster() ? Current.SapforEtalonVersion : Current.SapforVersion
                )));
        treePanel.repaint();
        treePanel.revalidate();
    }
    //---
    public void showNoTree() {
        UI.Clear(treePanel);
    }
    public void showObject() {
        lObjectName.setText(object.getPK().toString() + (isMaster() ? "(эталон)" : ""));
        lObjectName.setToolTipText(object.getPK().toString());
        //--
        if (object.package_json == null) {
            try {
                object.readJson();
                object.package_json.tasks.sort(Comparator.comparing(SapforTask::getUniqueKey));
                for (SapforTask task : object.package_json.tasks)
                    object.package_json.allTasks.put(task.getUniqueKey(), task);
                //---
                object.package_json.SortTasks(); //по состояниям конфигурациям и группам
                //---
                object.package_json.buildTree(object);
                //---
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        //--
        showCommonTree();
    }
    protected String getText() {
        return "";
    }
    public SapforPackagesComparisonForm(SapforPackagesComparisonForm slave_in) {
        //-
        this_ = this;
        slave = slave_in;
        bPrevious.setVisible(isMaster());
        bNext.setVisible(isMaster());
        bApplyObject.addActionListener(e -> {
            ApplyObject();
        });
        //--->>>
        if (isMaster()) {
            slave.master = this;
            bPrevious.addActionListener(e -> {
            });
            bNext.addActionListener(e -> {
            });
            bCompare.addActionListener(e -> {
                DoComparePass();
            });
        } else {
            //рабу сравнивать не положено.
            bCompare.setVisible(false);
        }
        //--->>>
        bClose.addActionListener(e -> {
            onClose();
        });
    }
    //-->>
    private void createUIComponents() {
        // TODO: place custom component creation code here
        lObjectName = new ShortLabel(40);
        tools = new VisualiserMenuBar();
    }
    //для сравнения по кнопке.
    public boolean isReady() {
        return object != null;
    }
    public void onClose() {
        RemoveObject();
    }
    public void DoComparePass() {
        Pass_2021 pass = new Pass_2021() {
            SapforPackage package1;
            SapforPackage package2;
            @Override
            public String getDescription() {
                return "Сравнение";
            }
            @Override
            protected boolean needsAnimation() {
                return true;
            }
            @Override
            public boolean needsConfirmations() {
                return false;
            }
            @Override
            protected boolean canStart(Object... args) throws Exception {
                if (isReady() && slave.isReady()) {
                    //--
                    package1 = object;
                    package2 = slave.object;
                    //--
                    if (!package1.testsIds.equals(package2.testsIds)) {
                        Log.Writeln_("Наборы тестов пакетов не совпадают!");
                        return false;
                    }
                    if (!package1.configurationsIds.equals(package2.configurationsIds)) {
                        Log.Writeln_("Наборы конфигураций не совпадают!");
                        return false;
                    }

                    for (String key1 : package1.package_json.allTasks.keySet()) {
                        if (!package2.package_json.allTasks.containsKey(key1)) {
                            Log.Writeln_("Задача эталона " + key1 + "не найдена в сравниваемом пакете!");
                        }
                    }
                    return Log.isEmpty();
                }
                return false;
            }
            @Override
            protected void performPreparation() throws Exception {
                comparisonMode = false;
                slave.comparisonMode = false;
                //--
                treeScroll = null;
                slave.treeScroll = null;
                //--
                package1.package_json.DropComparison();
                package2.package_json.DropComparison();
            }
            @Override
            protected void showPreparation() throws Exception {
                showNoTree();
                slave.showNoTree();
                //--->>>
                UI.getMainWindow().getTestingWindow().ShowNoSapforPackageVersionEtalon();
                UI.getMainWindow().getTestingWindow().ShowNoSapforPackageVersion();
            }
            @Override
            protected void body() throws Exception {

                System.out.println(package1.package_json.allTasks.size());
                System.out.println(package2.package_json.allTasks.size());
                //теперь сравниваем задачи
                int i = 1;
                for (String key1 : package1.package_json.allTasks.keySet()) {
                    System.out.println(i + "=" + key1);
                    SapforTask task1 = package1.package_json.allTasks.get(key1);
                    SapforTask task2 = package2.package_json.allTasks.get(key1);
                    //--
                    task1.checkMatch(task2);
                    //--
                    ++i;
                }
                //--
                package1.package_json.SortTasksForComparison();
                package2.package_json.SortTasksForComparison();
                //-
                package1.package_json.buildComparisonTree(package1);
                package2.package_json.buildComparisonTree(package2);

            }
            @Override
            protected boolean validate() {
                return Log.isEmpty();
            }
            @Override
            protected void showFail() throws Exception {
                showCommonTree();
                slave.showCommonTree();
            }
            @Override
            protected void performDone() throws Exception {
                comparisonMode = true;
                slave.comparisonMode = true;
                //--
            }
            @Override
            protected void showDone() throws Exception {
                showComparisonTree();
                slave.showComparisonTree();
                SynchronizeTrees();
            }
        };
        pass.Do();
    }
    public void SynchronizeTrees() {
        if (slave.Body != null) {
            Body.setSlaveTree(slave.Body);
            slave.treeScroll.getVerticalScrollBar().setModel(treeScroll.getVerticalScrollBar().getModel());
        }
    }
}
