package _VisualDVM.GlobalData;
import Common.Current_;
import Common.Database.VisualiserDatabase;
import Common.Utils.Utils_;
import _VisualDVM.Current;
import Common.Database.Objects.DBObject;
import _VisualDVM.Global;
import _VisualDVM.GlobalData.Account.Account;
import _VisualDVM.GlobalData.Account.AccountsDBTable;
import _VisualDVM.GlobalData.Compiler.CompilersDBTable;
import _VisualDVM.GlobalData.Credentials.Credentials;
import _VisualDVM.GlobalData.Credentials.CredentialsDBTable;
import _VisualDVM.GlobalData.DBLastProject.LastProjectsDBTable;
import _VisualDVM.GlobalData.DVMParameter.DVMParameterDBTable;
import _VisualDVM.GlobalData.EnvironmentValue.EnvironmentValuesDBTable;
import _VisualDVM.GlobalData.Machine.MachinesDBTable;
import _VisualDVM.GlobalData.Makefile.MakefilesDBTable;
import _VisualDVM.GlobalData.Module.ModulesDBTable;
import _VisualDVM.GlobalData.RunConfiguration.RunConfigurationsDBTable;
import _VisualDVM.GlobalData.SapforProfile.SapforProfile;
import _VisualDVM.GlobalData.SapforProfile.SapforProfilesDBTable;
import _VisualDVM.GlobalData.SapforProfileSetting.SapforProfileSetting;
import _VisualDVM.GlobalData.SapforProfileSetting.SapforProfileSettingsDBTable;
import _VisualDVM.GlobalData.Settings.DBSetting;
import _VisualDVM.GlobalData.Settings.SettingName;
import _VisualDVM.GlobalData.Settings.SettingsDBTable;
import _VisualDVM.GlobalData.Tasks.CompilationTask.CompilationTasksDBTable;
import _VisualDVM.GlobalData.Tasks.RunTask.RunTasksDBTable;
import _VisualDVM.GlobalData.User.UsersDBTable;
import _VisualDVM.Repository.Component.ComponentType;
import Visual_DVM_2021.PassStats.PassStatsDBTable;
import Visual_DVM_2021.Passes.PassCode;

import java.nio.file.Paths;
import java.util.Date;
import java.util.LinkedHashMap;
public class GlobalDatabase extends VisualiserDatabase {
    //---------СЕАНС----------------------------------------------
    public MachinesDBTable machines;
    public UsersDBTable users;
    public CompilersDBTable compilers;
    public MakefilesDBTable makefiles;
    public ModulesDBTable modules;
    public CompilationTasksDBTable compilationTasks;
    public RunTasksDBTable runTasks;
    public RunConfigurationsDBTable runConfigurations;
    public EnvironmentValuesDBTable environmentValues;
    public DVMParameterDBTable dvmParameters;
    public CredentialsDBTable credentials;
    //----- ДАННЫЕ ВИЗУАЛИЗАТОРА---------------------------------
    public SettingsDBTable settings;
    public LastProjectsDBTable lastProjects;
    public AccountsDBTable accounts;
    //-
    public SapforProfilesDBTable sapforProfiles = null;
    //---------
    public SapforProfileSettingsDBTable sapforProfilesSettings = null;
    //-
    public GlobalDatabase() {
        super(Paths.get(System.getProperty("user.dir"), "Data", "db7.sqlite").toFile());
    }
    @Override
    protected void initAllTables() throws Exception {
        super.initAllTables();
        addTable(machines = new MachinesDBTable());
        addTable(users = new UsersDBTable());
        addTable(compilers = new CompilersDBTable());
        addTable(makefiles = new MakefilesDBTable());
        addTable(modules = new ModulesDBTable());
        addTable(compilationTasks = new CompilationTasksDBTable());
        addTable(runTasks = new RunTasksDBTable());
        addTable(runConfigurations = new RunConfigurationsDBTable());
        addTable(environmentValues = new EnvironmentValuesDBTable());
        addTable(credentials = new CredentialsDBTable());
        addTable(settings = new SettingsDBTable());
        addTable(lastProjects = new LastProjectsDBTable());
        addTable(accounts = new AccountsDBTable());
        addTable(dvmParameters = new DVMParameterDBTable());
        addTable(sapforProfiles = new SapforProfilesDBTable());
        addTable(sapforProfilesSettings = new SapforProfileSettingsDBTable());
    }
    //---------------------------------------------------------------------------------
    @Override
    public void Init() throws Exception {
        Global.mainModule.set(Current.Account,
                accounts.Data.isEmpty() ? Insert(new Account()) :
                        accounts.getFirstRecord()
        );
        Global.mainModule.set(Current.Credentials,
                credentials.Data.isEmpty() ? Insert(new Credentials()) :
                        credentials.getFirstRecord());
        //настройки компонент
        settings.AddAll();
        runConfigurations.Patch();
    }
    @Override
    public PassCode getSynchronizePassCode() {
        return null;
    }
    public void SaveCredentials(){
        try {
            Credentials credentials = Global.mainModule.getCredentials();
            if (Global.mainModule.HasMachine())
                credentials.machine_id = Global.mainModule.getMachine().id;
            if (Global.mainModule.HasUser())
                credentials.user_id = Global.mainModule.getUser().id;
            if (Global.mainModule.HasCompiler())
                credentials.compiler_id = Global.mainModule.getCompiler().id;
            if (Global.mainModule.HasMakefile())
                credentials.makefile_id = Global.mainModule.getMakefile().id;
            if (Global.mainModule.HasRunConfiguration())
                credentials.runconfiguration_id = Global.mainModule.getRunConfiguration().id;
            Update(credentials);
        }
        catch (Exception ex){
            ex.printStackTrace();
        }
    }
    public void UpdateCredentials() {
        try {
            Update(Global.mainModule.getCredentials());
        } catch (Exception ex) {
            Utils_.MainLog.PrintException(ex);
        }
    }
    //--
    public LinkedHashMap<SettingName, String> getSapforSettingsForProfile() {
        LinkedHashMap<SettingName, String> res = new LinkedHashMap<>();
        for (DBSetting setting : settings.getSettingsByOwner(ComponentType.SapforOptions))
            if (setting.Visible)
                res.put(setting.Name, setting.Value);
        return res;
    }
    //проверить, есть ли профиль с таким же набором настроек.
    public SapforProfile checkProfileForCurrentSettings() {
        LinkedHashMap<SettingName, String> current_values = getSapforSettingsForProfile();
        for (SapforProfile profile : sapforProfiles.Data.values()) {
            //--получить все настройки профиля
            LinkedHashMap<SettingName, String> profileValues = new LinkedHashMap<>();
            for (SapforProfileSetting setting : sapforProfilesSettings.Data.values())
                if (setting.sapforprofile_id == profile.id) profileValues.put(setting.name, setting.value);
            //--
            if (current_values.equals(profileValues)) return profile;
        }
        return null;
    }
    public void insertProfileSettings(SapforProfile profile) throws Exception {
        LinkedHashMap<SettingName, String> current_values = getSapforSettingsForProfile();
        for (SettingName name : current_values.keySet()) {
            //--
            SapforProfileSetting sapforProfileSetting = new SapforProfileSetting();
            sapforProfileSetting.name = name;
            sapforProfileSetting.value = current_values.get(name);
            sapforProfileSetting.sapforprofile_id = profile.id;
            //--
            Insert(sapforProfileSetting);
        }
    }
    public void saveCurrentProfile(String name_in) throws Exception {
        if (checkProfileForCurrentSettings() == null) {
            SapforProfile profile = new SapforProfile();
            profile.description = name_in;
            profile.creationDate = new Date().getTime();
            Insert(profile);
            insertProfileSettings(profile);
        }
    }
    public void rewriteProfileByDescription(String description_in) throws Exception {
        SapforProfile old = null;
        //ищем профиль с именем бага
        for (SapforProfile p : sapforProfiles.Data.values())
            if (p.description.equalsIgnoreCase(description_in)) {
                old = p;
                break;
            }
        if (old != null) {
            //удалить профиль с именем бага,если есть, чтобы не множить кроликов.
            //при условии что не видно окна профилей!!
            Delete(old);
            DeleteByFK(old, SapforProfileSetting.class);
        }
        //---
        SapforProfile profile = new SapforProfile();
        profile.description = description_in;
        profile.creationDate = new Date().getTime();
        Insert(profile);
        insertProfileSettings(profile);
    }
}
