package Visual_DVM_2021.UI.Main;
import Common.Current;
import Common.Global;
import Common.UI.Menus_2023.MainMenuBar.MainWindow;
import Common.UI.UI;
import Common.UI.Windows.Form;
import Common.UI.Windows.FormType;
import Common.Utils.Utils;
import TestingSystem.Group.Group;
import TestingSystem.Test.Test;
import Visual_DVM_2021.Passes.PassCode_2021;
import Visual_DVM_2021.Passes.Pass_2021;
import Visual_DVM_2021.UI.Interface.*;

import javax.swing.*;
import java.awt.*;
import java.util.Vector;
public class MainForm extends Form implements MainWindow {
    private final WelcomeForm welcomeForm = new WelcomeForm(); //заглушка когда проекта нет.
    int global_index = 0;
    //-----------------
    private ProjectForm projectForm;
    private CallbackForm callbackForm;
    private CredentialsForm credentialsForm;
    private TestsForm testsForm;
    //---
    private TestingForm testingForm;
    //-----------------
    private JPanel Content;
    private JTabbedPane globalTabs;
    private JPanel mainPanel;

    @Override
    protected JPanel getMainPanel() {
        return Content;
    }
    @Override
    protected FormType getFormType() {
        return FormType.Main;
    }
    @Override
    public String getIconName() {
        return "Sapfor.png";
    }
    @Override
    public String getWTitleText() {
        return "Visual Sapfor 3.0";
    }
    @Override
    public String getUTitleText() {
        return "Visual Sapfor 3.0";
    }
    @Override
    public void AfterClose() {
        Pass_2021.passes.get(PassCode_2021.CloseCurrentProject).Do();
        if (UI.getVersionsWindow() != null)
            ((VersionsForm) UI.getVersionsWindow()).SaveSplitters();
        SaveCallbackPanel();
        SaveCredentialsPanel();
        SaveTestsPanel();
        SaveTestingPanel();
        //--
        if (UI.debugWindow!=null)
            ((FormWithSplitters) UI.debugWindow).SaveSplitters();
        //--
        Global.FinishApplication();
    }
    public MainForm() {
        mainPanel.add(UI.mainMenuBar, BorderLayout.NORTH);
        InstallWelcomePanel();
        InstallCallbackPanel();
        InstallCredentialsPanel();
        InstallTestsPanel();
        InstallTestingPanel();
        ShowUpdatesIcon();
        //----------------------
    }
    private void InstallWelcomePanel() {
        globalTabs.insertTab("Начало работы",
                null,
                welcomeForm.content,
                "Для начала работы откройте проект с помощью верхней панели инструментов, или перетащите его сюда", 0
        );
    }
    private void InstallProjectPanel() {
        globalTabs.insertTab("", null,
                (projectForm = new ProjectForm()).content, Current.getProject().description, 0);
        globalTabs.setTabComponentAt(0,
                new TabToolBar("Проект: " + Current.getProject().name, PassCode_2021.CloseCurrentProject) {
                    @Override
                    public void leftMouseAction() {
                        globalTabs.setSelectedIndex(0);
                    }
                });
    }
    private void RemoveProjectPanel() {
        globalTabs.removeTabAt(0);
        if (projectForm != null) {
            projectForm.SaveSplitters();
            projectForm = null;
        }
    }
    private void InstallCallbackPanel() {
        globalTabs.insertTab("Обратная связь",
                Utils.getIcon("/icons/Bug.png"),
                (callbackForm = new CallbackForm()).getContent(),
                "Журнал ошибок и связь с разработчиками", 1);
    }
    private void SaveCallbackPanel() {
        if (callbackForm != null) {
            callbackForm.SaveSplitters();
            callbackForm = null;
        }
    }
    private void InstallCredentialsPanel() {
        globalTabs.insertTab("Машины",
                Utils.getIcon("/icons/Machine.png"),
                (credentialsForm = new CredentialsForm()).getContent(),
                "Машины, пользователи, компиляторы", 2);
    }
    private void SaveCredentialsPanel() {
        if (credentialsForm != null) {
            credentialsForm.SaveSplitters();
            credentialsForm = null;
        }
    }
    private void InstallTestsPanel() {
        globalTabs.insertTab("Тесты",
                Utils.getIcon("/icons/Library.PNG"),
                (testsForm = new TestsForm()).getContent(),
                "Библиотека тестов на сервере", 3);
    }
    private void SaveTestsPanel() {
        if (testsForm != null) {
            testsForm.SaveSplitters();
            testsForm = null;
        }
    }
    private void InstallTestingPanel() {
        testingForm = new TestingForm();
        ShowTestingTab();
    }
    @Override
    public void ShowTestingTab() {
        if (globalTabs.getTabCount() < 5)
            globalTabs.insertTab("Тестирование",
                    Utils.getIcon("/icons/Session.png"),
                    testingForm.getContent(),
                    "Система тестирования", 4);
    }
    @Override
    public void HideTestingTab() {
        if (globalTabs.getTabCount() == 5)
            globalTabs.removeTabAt(4);
    }
    @Override
    public void ShowCredentials() {
        /*
        String res = "";
        if (Current.HasMachine()) {
            res += "@" + Current.getMachine().getURL();
            if (Current.HasUser()) {
                res = Current.getUser().login + res;
            } else res = "?" + res;
            /*
            if (Current.HasCompiler() && Current.getCompiler().type.equals(CompilerType.dvm)) {
                testingTabs.setTitleAt(3, "DVM система: " + Current.getCompiler().description);
            } else {
                testingTabs.setTitleAt(3, "DVM система: ?");
            }
             */
        /*д
        } else {
            res += "?@?";
        }
        globalTabs.setTitleAt(2, res);
    */
    }
    @Override
    public void ShowCheckedTestsCount() {
        int res = 0;
        for (Group group : Global.testingServer.db.groups.getCheckedItems()) {
            Vector<Test> selected_tests = new Vector<>();
            Vector<Test> group_tests = new Vector<>();
            for (Test test : Global.testingServer.db.tests.Data.values()) {
                if (test.group_id.equals(group.id)) {
                    if (test.isSelected())
                        selected_tests.add(test);
                    else
                        group_tests.add(test);
                }
            }
            //-
            if (selected_tests.isEmpty())
                res += group_tests.size();
            else
                res += selected_tests.size();
        }
        //--
        globalTabs.setTitleAt(3, "Тесты: " + res);
    }
    private void SaveTestingPanel() {
        if (testingForm != null) {
            testingForm.SaveSplitters();
            testingForm = null;
        }
    }
    private void saveGlobalTab() {
        global_index = globalTabs.getSelectedIndex();
    }
    private void restoreGlobalTab() {
        globalTabs.setSelectedIndex(global_index);
    }
    @Override
    public ProjectWindow getProjectWindow() {
        return projectForm;
    }
    @Override
    public CallbackWindow getCallbackWindow() {
        return callbackForm;
    }
    @Override
    public CredentialsWindow getCredentialsWindow() {
        return credentialsForm;
    }
    @Override
    public TestsWindow getTestsWindow() {
        return testsForm;
    }
    @Override
    public void ShowUpdatesIcon() {
        UI.mainMenuBar.ShowUpdatesIcon();
    }
    @Override
    public void FocusProject() {
        globalTabs.setSelectedIndex(0);
    }
    @Override
    public void FocusCallback() {
        globalTabs.setSelectedIndex(1);
    }
    @Override
    public void FocusTesting() {
        globalTabs.setSelectedIndex(3);
    }
    @Override
    public TestingWindow getTestingWindow() {
        return testingForm;
    }
    @Override
    public void Show() {
        //приходится идти на это только ПОСЛЕ создания главного окна.
        // иначе ссылка на главное окно в методах пустая.
        getCallbackWindow().ShowAll();
        getCredentialsWindow().ShowAll();
        getTestsWindow().ShowAll();
        if (getTestingWindow() != null)
            getTestingWindow().ShowAll();
        UI.windowsStack.push(this);
        System.out.println("New Front Window");
        super.Show();
    }
    @Override
    public void ShowProject() {
        //-
        saveGlobalTab();
        RemoveProjectPanel();
        InstallProjectPanel();
        restoreGlobalTab();
        UI.getDebugWindow().DropCompilationTasksComparison();
        UI.mainMenuBar.ShowProject(true);
    }
    @Override
    public void ShowNoProject() {
        //-
        saveGlobalTab();
        RemoveProjectPanel();
        InstallWelcomePanel();
        restoreGlobalTab();
        UI.mainMenuBar.ShowProject(false);
    }
}
