package _VisualDVM;
import Common.Utils.Utils_;
import Common.Visual.Controls.StableMenuItem;
import _VisualDVM.Passes.PassCode;
import com.google.gson.annotations.Expose;

import javax.swing.*;
import java.io.File;
import java.lang.reflect.Field;
import java.nio.file.Paths;
public class GlobalProperties {
    @Expose
    public _VisualDVM.Mode Mode = _VisualDVM.Mode.Normal;
    @Expose
    public String ServerAddress = "alex-freenas.ddns.net";
    @Expose
    public String ServerUserName = "testuser";
    @Expose
    public int ServerUserSHHPort = 23;
    @Expose
    public int ComponentsServerPort = 7995;
    @Expose
    public int TestingServerPort = 7998;
    @Expose
    public int SocketTimeout = 5000;
    @Expose
    public boolean OldServer = false;
    @Expose
    public String SMTPHost = "smtp.mail.ru";
    @Expose
    public int SMTPPort = 465;
    @Expose
    public int MailSocketPort = 465;
    @Expose
    public boolean collapseCredentials = false;
    @Expose
    public boolean collapseFileGraphs = false;
    @Expose
    public boolean collapseFileMessages = false;
    @Expose
    public boolean collapseProjectTrees = false;
    @Expose
    public String BackupWorkspace = "_sapfor_x64_backups";
    @Expose
    public int BackupHour = 5;
    @Expose
    public int BackupMinute = 0;
    @Expose
    public boolean EmailAdminsOnStart = false;
    @Expose
    public boolean AutoUpdateSearch = true;
    @Expose
    public boolean ConfirmPassesStart = true;
    @Expose
    public boolean ShowPassesDone = true;
    @Expose
    public boolean FocusPassesResult = true;
    @Expose
    public String ProjectDBName = "new_project_base.sqlite";
    @Expose
    public String BugReportsDBName = "bug_reports.sqlite";
    @Expose
    public String TestsDBName = "tests.sqlite";
    @Expose
    public int ComponentsWindowWidth = 650;
    @Expose
    public int ComponentsWindowHeight = 250;
    @Expose
    public String VisualiserPath = "";
    @Expose
    public String Sapfor_FPath = "";
    @Expose
    public String Visualizer_2Path = "";
    @Expose
    public String InstructionPath = "";
    @Expose
    public String PerformanceAnalyzerPath = "";
    @Expose
    public int ComponentsBackUpsCount = 10;
    @Expose
    public boolean AutoCheckTesting = false; // проверять ли задачи тестирования при включенном визуализаторе.
    @Expose
    public int CheckTestingIntervalSeconds = 10; //интервал автопроверки тестирования
    @Expose
    public boolean EmailOnTestingProgress = false; //включено ли оповещение по email о результатах тестирования.
    @Expose
    public boolean eraseTestingWorkspaces = true; //удалять ли рабочее пространство пакетов тестирования после его завершения
    public GlobalProperties(GlobalProperties p) {
        super();
        Mode = p.Mode;
        ServerAddress = p.ServerAddress;
        ServerUserName = p.ServerUserName;
        ServerUserSHHPort = p.ServerUserSHHPort;
        ComponentsServerPort = p.ComponentsServerPort;
        TestingServerPort = p.TestingServerPort;
        SocketTimeout = p.SocketTimeout;
        OldServer = p.OldServer;
        SMTPHost = p.SMTPHost;
        SMTPPort = p.SMTPPort;
        MailSocketPort = p.MailSocketPort;
        collapseCredentials = p.collapseCredentials;
        collapseFileGraphs = p.collapseFileGraphs;
        collapseFileMessages = p.collapseFileMessages;
        collapseProjectTrees = p.collapseProjectTrees;
        BackupWorkspace = p.BackupWorkspace;
        BackupHour = p.BackupHour;
        BackupMinute = p.BackupMinute;
        EmailAdminsOnStart = p.EmailAdminsOnStart;
        AutoUpdateSearch = p.AutoUpdateSearch;
        ConfirmPassesStart = p.ConfirmPassesStart;
        ShowPassesDone = p.ShowPassesDone;
        FocusPassesResult = p.FocusPassesResult;
        ProjectDBName = p.ProjectDBName;
        BugReportsDBName = p.BugReportsDBName;
        TestsDBName = p.TestsDBName;
        ComponentsWindowWidth = p.ComponentsWindowWidth;
        ComponentsWindowHeight = p.ComponentsWindowHeight;
        VisualiserPath = p.VisualiserPath;
        Sapfor_FPath = p.Sapfor_FPath;
        Visualizer_2Path = p.Visualizer_2Path;
        InstructionPath = p.InstructionPath;
        PerformanceAnalyzerPath = p.PerformanceAnalyzerPath;
        ComponentsBackUpsCount = p.ComponentsBackUpsCount;
        AutoCheckTesting = p.AutoCheckTesting;
        CheckTestingIntervalSeconds = p.CheckTestingIntervalSeconds;
        EmailOnTestingProgress = p.EmailOnTestingProgress;
        eraseTestingWorkspaces = p.eraseTestingWorkspaces;
    }
    //--
    public GlobalProperties() {
    }
    //-----------------
    public String getFieldDescription(String fieldName) {
        switch (fieldName) {
            case "ShowPassesDone":
                return "Сообщать об успешном выполнении проходов";
            case "ConfirmPassesStart":
                return "Запрашивать подтверждения начала выполнения проходов";
            case "FocusPassesResult":
                return "Переходить на результирующую вкладку проходов по их завершении";
            case "collapseCredentials":
                return "Свернуть раздел машин";
            case "collapseFileGraphs":
                return "Свернуть раздел графов файла";
            case "collapseFileMessages":
                return "Свернуть раздел сообщений файла";
            case "collapseProjectTrees":
                return "Свернуть раздел деревьев проекта";
            default:
                return "?";
        }
    }
    //-----------------
    public void addFlagMenuItem(JMenu menu, String fieldName) {
        JMenuItem menu_item = new StableMenuItem(getFieldDescription(fieldName),
                getFlag(fieldName) ? "/Common/icons/Pick.png" : "/Common/icons/NotPick.png");
        //-
        menu_item.addActionListener(e -> {
            if (Global.mainModule.getPass(PassCode.UpdateProperty).Do(fieldName, !getFlag(fieldName)))
                menu_item.setIcon(Utils_.getIcon(getFlag(fieldName) ? "/Common/icons/Pick.png" : "/Common/icons/NotPick.png"));
        });
        menu.add(menu_item);
    }
    public boolean getFlag(String fieldName) {
        boolean field = false;
        try {
            field = (boolean) getClass().getField(fieldName).get(this);
            //
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return field;
    }
    public void switchFlag(String fieldName) {
        boolean field = false;
        try {
            field = (boolean) getClass().getField(fieldName).get(this);
            getClass().getField(fieldName).set(this, !field);
            //
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    public void Update() {
        try {
            Utils_.jsonToFile(this, getFile());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //--
    public boolean updateField(String name, Object newValue) {
        try {
            Field field = getClass().getField(name);
            Object oldValue = field.get(this);
            //---
            if (newValue.equals(oldValue))
                return false;
            //--
            field.set(this, newValue);
            this.Update();
            return true;
            //--
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return false;
    }
    public void switchAndUpdateFlag(String name) {
        try {
            Field field = getClass().getField(name);
            boolean oldValue = (boolean) field.get(this);
            boolean newValue = !oldValue;
            //---
            field.set(this, newValue);
            this.Update();
            //--
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
    public File getFile() {
        return Paths.get(System.getProperty("user.dir"), "properties").toFile();
    }
}
