package _VisualDVM;
import Common.Database.Tables.DataSet;
import Common.Utils.Loggable;
import Common.Utils.Utils_;
import Common.Visual.UI_;
import _VisualDVM.GlobalData.Account.Account;
import _VisualDVM.GlobalData.Account.AccountRole;
import _VisualDVM.GlobalData.Settings.DBSetting;
import _VisualDVM.GlobalData.Settings.SettingName;
import _VisualDVM.Passes.PassCode;
import _VisualDVM.ProjectData.ProjectView;
import _VisualDVM.Repository.Component.*;
import _VisualDVM.Repository.Component.PerformanceAnalyzer.PerformanceAnalyzer;
import _VisualDVM.Repository.Component.Sapfor.MessagesServer;
import _VisualDVM.Repository.Component.Sapfor.Sapfor_F;
import _VisualDVM.Repository.Component.Sapfor.TransformationPermission;
import _VisualDVM.Repository.Server.ComponentsServer;
import _VisualDVM.TestingSystem.Common.TestingServer;
import _VisualDVM.TestingSystem.DVM.LocalDVMTestingPlanner;
import _VisualDVM.TestingSystem.DVM.RemoteDVMTestingPlanner;
import _VisualDVM.TestingSystem.SAPFOR.PackageModeSupervisor;
import _VisualDVM.Visual.UI;
import org.fife.ui.rsyntaxtextarea.AbstractTokenMakerFactory;
import org.fife.ui.rsyntaxtextarea.TokenMakerFactory;

import java.io.File;
import java.nio.file.Paths;
import java.util.Vector;
public class Global {
    public static MainModule mainModule = null;
    //Режим
    public static Mode mode = Mode.Undefined;
    //--------------------------------------------------
    public static GlobalProperties properties = new GlobalProperties();
    //</editor-fold>
    //------------------------------------------------------
    public static boolean enable_text_changed = false;
    //---
    public static boolean files_multiselection = false;
    public static boolean versions_multiselection = false;
    //---
    public static TransformationPermission transformationPermission = TransformationPermission.None;
    //??
    public static DataSet<ComponentType, Component> Components = null;
    public static MessagesServer messagesServer = null;
    public static File ComponentsDirectory;
    public static File DataDirectory;
    public static File BugReportsDirectory;
    public static File BackUpsDirectory;
    public static File TempDirectory;
    public static File ProjectsDirectory;
    public static File CompilationTasksDirectory;
    public static File RunTasksDirectory;
    public static File StsDirectory;
    public static File RepoDirectory;
    public static File TestsDirectory;
    public static File PerformanceAnalyzerDirectory;
    public static File DataBackUpsDirectory;
    public static File DVMPackagesDirectory;
    public static File SapforsDirectory;
    public static File SapforPackagesDirectory;
    public static File MachinesDirectory;
    //------------------------------------------------------------------
    public static Visualiser visualiser = null;
    public static Visualizer_2 visualizer_2 = null;
    public static PerformanceAnalyzer performanceAnalyzer = null;
    //------------------------------------------------------------------
    public static ComponentsServer componentsServer = new ComponentsServer();
    public static TestingServer testingServer = new TestingServer();
    public static int bad_state = 0;
    public static int need_update = 0;
    public static int need_publish = 0;
    public static void SynschronizeProperties() {
        try {
            File new_propertiesFile = new File(Utils_.getHomeDirectory(), "properties");
            if (new_propertiesFile.exists())
                properties = (GlobalProperties) Utils_.jsonFromFile(new_propertiesFile, GlobalProperties.class);
            Utils_.jsonToFile(properties, new_propertiesFile);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    public static void CheckVisualiserDirectories() {
        Utils_.CheckDirectory(ComponentsDirectory = new File(Utils_.getHomeDirectory(), Constants.ComponentsDirectoryName));
        Utils_.CheckAndCleanDirectory(TempDirectory = new File(Utils_.getHomeDirectory(), Constants.TempDirectoryName));
        Utils_.CheckDirectory(DataDirectory = new File(Utils_.getHomeDirectory(), Constants.DataDirectoryName));
        //-
        Utils_.CheckDirectory(RepoDirectory = new File(Utils_.getHomeDirectory(), Constants.RepoDirectoryName));
        Utils_.CheckDirectory(BugReportsDirectory = new File(Utils_.getHomeDirectory(), Constants.BugsDirectoryName));
        Utils_.CheckDirectory(BackUpsDirectory = new File(Utils_.getHomeDirectory(), Constants.BackUpsDirectoryName));
        Utils_.CheckDirectory(ProjectsDirectory = new File(Utils_.getHomeDirectory(), Constants.ProjectsDirectoryName));
        Utils_.CheckDirectory(CompilationTasksDirectory = new File(Utils_.getHomeDirectory(), Constants.CompilationTasksDirectoryName));
        Utils_.CheckDirectory(RunTasksDirectory = new File(Utils_.getHomeDirectory(), Constants.RunTasksDirectoryName));
        Utils_.CheckDirectory(StsDirectory = new File(Utils_.getHomeDirectory(), Constants.StsDirectoryName));
        Utils_.CheckDirectory(TestsDirectory = new File(Utils_.getHomeDirectory(), Constants.TestsDirectoryName));
        Utils_.CheckDirectory(PerformanceAnalyzerDirectory = new File(Utils_.getHomeDirectory(), Constants.PerformanceAnalyzerDirectoryName));
        Utils_.CheckDirectory(DVMPackagesDirectory = new File(Utils_.getHomeDirectory(), Constants.DVMPackagesDirectoryName));
        //через пару версий заменить на clean.
        Utils_.CheckDirectory(SapforPackagesDirectory = new File(Utils_.getHomeDirectory(), "SapforPackages"));
        Utils_.CheckDirectory(MachinesDirectory = new File(Utils_.getHomeDirectory(), "Machines"));
    }
    public static void CheckServerDirectories() {
        Utils_.CheckDirectory(ComponentsDirectory = new File(Utils_.getHomeDirectory(), Constants.ComponentsDirectoryName));
        Utils_.CheckAndCleanDirectory(TempDirectory = new File(Utils_.getHomeDirectory(), Constants.TempDirectoryName));
        Utils_.CheckDirectory(DataDirectory = new File(Utils_.getHomeDirectory(), Constants.DataDirectoryName));
        //-
        Utils_.CheckDirectory(BugReportsDirectory = new File(Utils_.getHomeDirectory(), Constants.BugsDirectoryName));
        Utils_.CheckDirectory(DataBackUpsDirectory = new File(Utils_.getHomeDirectory(), Constants.DataBackUpsDirectoryName));
        Utils_.CheckDirectory(MachinesDirectory = new File(Utils_.getHomeDirectory(), "Machines"));
    }
    public static void CheckTestingSystemDirectories() {
        Utils_.CheckDirectory(ComponentsDirectory = new File(Utils_.getHomeDirectory(), Constants.ComponentsDirectoryName));
        Utils_.CheckAndCleanDirectory(TempDirectory = new File(Utils_.getHomeDirectory(), Constants.TempDirectoryName));
        Utils_.CheckDirectory(DataDirectory = new File(Utils_.getHomeDirectory(), Constants.DataDirectoryName));
        //-
        Utils_.CheckDirectory(TestsDirectory = new File(Utils_.getHomeDirectory(), Constants.TestsDirectoryName));
        Utils_.CheckDirectory(RepoDirectory = new File(Utils_.getHomeDirectory(), Constants.RepoDirectoryName));
        Utils_.CheckDirectory(DVMPackagesDirectory = new File(Utils_.getHomeDirectory(), Constants.DVMPackagesDirectoryName));
        Utils_.CheckDirectory(SapforsDirectory = new File(Utils_.getHomeDirectory(), "Sapfors"));
        Utils_.CheckDirectory(SapforPackagesDirectory = new File(Utils_.getHomeDirectory(), "SapforPackages"));
        //CheclAndClean через неделю
        Utils_.CheckDirectory(MachinesDirectory = new File(Utils_.getHomeDirectory(), "Machines"));
    }
    public static void CreateLogAtComponentsPath() {
        Utils_.MainLog = new Loggable() {
            @Override
            public String getLogHomePath() {
                return Paths.get(System.getProperty("user.dir"), "Components").toString();
            }
            @Override
            public String getLogName() {
                return "VisualDVM";
            }
        };
        Utils_.MainLog.ClearLog();
    }
    public static void CreateLogAtHome() {
        Utils_.MainLog = new Loggable() {
            @Override
            public String getLogHomePath() {
                return Utils_.getHomePath();
            }
            @Override
            public String getLogName() {
                return mode.toString();
            }
        };
        Utils_.MainLog.ClearLog();
    }
    //-
    public static void FinishApplication() {
        try {
            mainModule.DeactivateDB();
            if (componentsServer.db != null)
                componentsServer.db.Disconnect();
            if (testingServer.db != null)
                testingServer.db.Disconnect();
            if (visualizer_2 != null)
                visualizer_2.Shutdown();
            if (messagesServer != null)
                messagesServer.Shutdown();
            if (performanceAnalyzer != null)
                performanceAnalyzer.Shutdown();
        } catch (Exception ex) {
            if (Utils_.MainLog != null) {
                Utils_.MainLog.PrintException(ex);
            } else {
                ex.printStackTrace();
            }
        }
        System.exit(0);
    }
    public static void RefreshUpdatesStatus() {
        Components.RefreshUI();
        ValidateComponentsStates();
        if (UI.HasMainWindow())
            UI.getMainWindow().ShowUpdatesIcon();
    }
    public static boolean ValidateComponentsStates() {
        bad_state = need_update = need_publish = 0;
        for (Component component : Components.Data.values()) {
            if (component.isVisible()) {
                switch (component.getState()) {
                    case Not_found:
                    case Unknown_version:
                    case Old_version:
                        if (component.isNecessary())
                            bad_state++;
                        component.Select(true);
                        break;
                    case Needs_update:
                        need_update++;
                        component.Select(true);
                        break;
                    case Needs_publish:
                        need_publish++;
                        break;
                    default:
                        component.Select(false);
                        break;
                }
            }
        }
        return (bad_state == 0);
    }
    public static void changeSetting(SettingName settingName, Object new_value) throws Exception {
        Global.mainModule.getPass(PassCode.UpdateSetting).Do(settingName, new_value);
    }
    public static String packSapforSettings() {
        Vector<String> res_ = new Vector<>();
        Vector<SettingName> forbidden = new Vector<>();
        forbidden.add(SettingName.GCOVLimit);
        forbidden.add(SettingName.Precompilation);
        forbidden.add(SettingName.DVMConvertationOptions);
        forbidden.add(SettingName.SaveModifications);
        for (DBSetting setting : mainModule.getDb().settings.getSettingsByOwner(ComponentType.SapforOptions)) {
            if (!forbidden.contains(setting.Name))
                res_.add(setting.Value);
        }
        return String.join("|", res_);
    }
    //--
    public static void NormalMode(int port) throws Exception {
        //-------------------------------->>
        UI_.active = true;
        mainModule = new MainModule();
        mainModule.CreateAll();
        //--
        CheckVisualiserDirectories();
        CreateLogAtComponentsPath();
        //-
        visualizer_2 = new Visualizer_2(port);
        visualizer_2.Connect();
        visualizer_2.refreshPid();
        //если делать раньше, то не удастся убить сервер.
        if (Utils_.ContainsCyrillic(Utils_.getHomePath())) {
            UI_.Info("В пути к корневой папке " + Utils_.DQuotes(Utils_.getHomePath()) + "\n" +
                    "Найдены русские буквы.\n" +
                    "Визуализатор завершает работу."); //
            FinishApplication();
        }
        messagesServer = new MessagesServer();
        messagesServer.Start();
        //создание списков служебных объектов
        UI.CreateAll();
        //единственное меню до остальных.
        Components = new ComponentsSet();
        mainModule.set(Current.ProjectView, ProjectView.Files);
        Components.put(ComponentType.Visualiser, visualiser = new Visualiser());
        Components.put(ComponentType.Sapfor_F, (Component) mainModule.set(Current.Sapfor, new Sapfor_F()));
        Components.put(ComponentType.Visualizer_2, visualizer_2);
        Components.put(ComponentType.PerformanceAnalyzer, performanceAnalyzer = new PerformanceAnalyzer());
        Components.put(ComponentType.Instruction, new Instruction());
        //-
        for (Component component : Components.Data.values())
            if (component.isVisible()) component.InitialVersionCheck();
        //-
        UI.CreateComponentsForm();
        AbstractTokenMakerFactory atmf = (AbstractTokenMakerFactory) TokenMakerFactory.getDefaultInstance();
        atmf.putMapping("text/FortranSPF", "_VisualDVM.Visual.Syntax.FortranSPFTokenMaker");
        atmf.putMapping("text/FreeFortranSPF", "_VisualDVM.Visual.Syntax.FreeFortranSPFTokenMaker");
        //  FoldParserManager.get().addFoldParserMapping("text/FortranSPF", new FortranFolder()); блоки кода. todo
        //light_editor.xml-------->>
        //-------->>
        if (properties.AutoUpdateSearch)
            Global.mainModule.getPass(PassCode.GetComponentsActualVersions).Do();
        ValidateComponentsStates();
        if ((need_update > 0) || (bad_state > 0)) {
            boolean flag = true;
            do {
                UI.ShowComponentsWindow();
                if (flag = (!ValidateComponentsStates())) {
                    if (!UI_.Question("Найдено " + bad_state + " некорректных необходимых компонент.Работа визуализатора невозможна.\n" +
                            "Вернуться к окну компонент"
                    )) {
                        UI_.Info("Визуализатор завершает работу.");
                        FinishApplication();
                    }
                }
            } while (flag);
        }
        mainModule.ActivateDB();
        mainModule.set(Current.Account, new Account() {
            {
                name = "M";
                email = "vmk-post@yandex.ru";
                role = AccountRole.Admin;
            }
        });
        //  Pass_2021.passes.get(PassCode_2021.CheckAccount).Do();
        //---------------
        componentsServer.ActivateDB();
        testingServer.ActivateDB();
        //в проперти их!
        //-- чисто чтобы создать таблицы. соединения на стороне клиента не предвидится.
        if (mainModule.getDb().settings.get(SettingName.AutoBugReportsLoad).toBoolean())
            Global.mainModule.getPass(PassCode.SynchronizeBugReports).Do();
        //--
        if (mainModule.getDb().settings.get(SettingName.AutoTestsLoad).toBoolean())
            Global.mainModule.getPass(PassCode.SynchronizeTests).Do();
        Global.mainModule.getSapfor().refreshPid(); //без сапфора сюда это все равно не дойдет.
        UI.CreateMenus();
        UI.CreateWindows();
    }
    public static void ServerMode() throws Exception {
        CheckServerDirectories();
        CreateLogAtComponentsPath();
        componentsServer = new ComponentsServer();
        componentsServer.ActivateDB();
        componentsServer.Start();
        System.exit(0);
    }
    public static void TestingSystemMode() throws Exception {
        CheckTestingSystemDirectories();
        CreateLogAtComponentsPath();
        testingServer = new TestingServer();
        testingServer.ActivateDB();
        //   testingServer.PATCH();
        testingServer.Start();
        System.exit(0);
    }
    //режим запуска пакета Сапфор
    public static void PackageMode() throws Exception {
        CreateLogAtHome();
        PackageModeSupervisor planner = new PackageModeSupervisor();
        planner.Start();
    }
    public static void MachineQueueMode(String... args) throws Exception {
        RemoteDVMTestingPlanner supervisor = new RemoteDVMTestingPlanner(args);
        while (true) {
            supervisor.Perform();
        }
    }
    public static void LocalMachineQueueMode(String... args) throws Exception {
        LocalDVMTestingPlanner supervisor = new LocalDVMTestingPlanner(args);
        while (true) {
            supervisor.Perform();
        }
    }
    //---
    public static void Init(String... args) {
        System.out.println("VisualSapfor.jar started..");
        System.out.println("home directory is" + Utils_.Brackets(Utils_.getHomePath()));
        //---
        SynschronizeProperties();
        mode = properties.Mode;
        System.out.println("mode is " + mode);
        try {
            switch (mode) {
                case Normal:
                    NormalMode(Integer.parseInt(args[1]));
                    break;
                case Server:
                    ServerMode();
                    break;
                case Testing:
                    TestingSystemMode();
                    break;
                case Package:
                    PackageMode();
                    break;
                case MachineQueue:
                    MachineQueueMode(args);
                    break;
                case LocalMachineQueue:
                    LocalMachineQueueMode(args);
                    break;
                case Undefined:
                    break;
            }
        } catch (Exception ex) {
            System.out.println("VISUALISER FAILED");
            ex.printStackTrace();
            if (Utils_.MainLog != null)
                Utils_.MainLog.PrintException(ex);
            FinishApplication();
        }
    }
}
