<commit_before>﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEngine;
using KSP;
using Contracts;
using FinePrint;
using FinePrint.Utilities;

namespace WaypointManager
{
    [KSPAddon(KSPAddon.Startup.SpaceCentre, true)]
    class WaypointManager : MonoBehaviour
    {
        private const float GUI_WIDTH = 360;
        private const float SETTINGS_WIDTH = 280;

        public static WaypointManager Instance;

        private ApplicationLauncherButton launcherButton = null;
        private IButton toolbarButton;

        private bool initialized = false;
        public bool showGUI = false;
        private bool showSettings = false;
        public bool visible = true;
        private bool stylesSetup = false;

        private GUIStyle headerButtonStyle;
        private GUIStyle labelStyle;
        private GUIStyle headingStyle;
        private GUIStyle tipStyle;

        private Vector2 scrollPosition;
        private Rect settingsPosition;

        private Rect tooltipPosition;
        private List<string> toolTip = new List<string>();
        private List<double> toolTipTime = new List<double>();

        static Dictionary<string, Texture2D> bodyIcons = new Dictionary<string, Texture2D>();
        static Dictionary<CelestialBody, bool> hiddenBodies = new Dictionary<CelestialBody, bool>();

        void Start()
        {
            DontDestroyOnLoad(this);

            if (!initialized)
            {
                LoadTextures();
                LoadConfiguration();
                LoadToolbar();

                GameEvents.onGUIApplicationLauncherReady.Add(new EventVoid.OnEvent(SetupToolbar));
                GameEvents.onGUIApplicationLauncherUnreadifying.Add(new EventData<GameScenes>.OnEvent(TeardownToolbar));
                GameEvents.onGameSceneLoadRequested.Add(new EventData<GameScenes>.OnEvent(OnGameSceneLoad));
                GameEvents.onHideUI.Add(new EventVoid.OnEvent(OnHideUI));
                GameEvents.onShowUI.Add(new EventVoid.OnEvent(OnShowUI));
                GameEvents.onPlanetariumTargetChanged.Add(new EventData<MapObject>.OnEvent(PlanetariumTargetChanged));

                Config.Load();

                Instance = this;
                initialized = true;
            }
        }

        void OnDestroy()
        {
            GameEvents.onGUIApplicationLauncherReady.Remove(new EventVoid.OnEvent(SetupToolbar));
            GameEvents.onGUIApplicationLauncherUnreadifying.Remove(new EventData<GameScenes>.OnEvent(TeardownToolbar));
            GameEvents.onHideUI.Remove(OnHideUI);
            GameEvents.onShowUI.Remove(OnShowUI);
            GameEvents.onPlanetariumTargetChanged.Remove(new EventData<MapObject>.OnEvent(PlanetariumTargetChanged));

            UnloadToolbar();

            Config.Save();
        }

        private void LoadTextures()
        {
            Config.toolbarIcon = GameDatabase.Instance.GetTexture("WaypointManager/icons/toolbar", false);
            Config.addWaypointIcon = GameDatabase.Instance.GetTexture("WaypointManager/icons/addWaypoint", false);
            Config.editWaypointIcon = GameDatabase.Instance.GetTexture("WaypointManager/icons/editWaypoint", false);
            Config.deleteWaypointIcon = GameDatabase.Instance.GetTexture("WaypointManager/icons/deleteWaypoint", false);
            Config.settingsIcon = GameDatabase.Instance.GetTexture("WaypointManager/icons/settings", false);
            Config.closeIcon = GameDatabase.Instance.GetTexture("WaypointManager/icons/close", false);
        }

        private void SetupToolbar()
        {
            if (launcherButton == null && Config.useStockToolbar)
            {
                ApplicationLauncher.AppScenes visibleScenes = ApplicationLauncher.AppScenes.FLIGHT |
                    ApplicationLauncher.AppScenes.MAPVIEW |
                    ApplicationLauncher.AppScenes.TRACKSTATION;
                launcherButton = ApplicationLauncher.Instance.AddModApplication(ToggleWindow, ToggleWindow, null, null, null, null,
                    visibleScenes, Config.toolbarIcon);
            }
        }

        private void TeardownToolbar(GameScenes scene)
        {
            if (launcherButton != null)
            {
                ApplicationLauncher.Instance.RemoveModApplication(launcherButton);
                launcherButton = null;
            }
        }

        private void LoadToolbar()
        {
            if (ToolbarManager.ToolbarAvailable)
            {
                toolbarButton = ToolbarManager.Instance.add("WaypointManager", "button");
                toolbarButton.TexturePath = "WaypointManager/icons/toolbarSmall";
                toolbarButton.ToolTip = "Waypoint Manager";
                toolbarButton.Visibility = new GameScenesVisibility(GameScenes.FLIGHT, GameScenes.TRACKSTATION);
                toolbarButton.OnClick += (e) =>
                {
                    ToggleWindow();
                };
            }
        }

        private void UnloadToolbar()
        {
            toolbarButton.Destroy();
            toolbarButton = null;
        }

        private void OnGameSceneLoad(GameScenes scene)
        {
            if (scene != GameScenes.FLIGHT && scene != GameScenes.TRACKSTATION)
            {
                showGUI = false;
                showSettings = false;
                Config.Save();
            }
        }

        private void PlanetariumTargetChanged(MapObject mapObject)
        {
            CustomWaypointGUI.MapObject = mapObject;
        }

        /// <summary>
        /// Loads external config node data.
        /// </summary>
        void LoadConfiguration()
        {
            // Load all the celestial body configuration
            ConfigNode[] bodyConfig = GameDatabase.Instance.GetConfigNodes("WAYPOINT_MANAGER_BODIES");
            foreach (ConfigNode configNode in bodyConfig)
            {
                try
                {
                    string config = configNode.GetValue("name");

                    Debug.Log("WaypointManager: Loading " + config +" icons.");
                    string url = configNode.GetValue("url");
                    if (url.Last() != '/')
                    {
                        url += '/';
                    }
                    foreach (GameDatabase.TextureInfo icon in GameDatabase.Instance.GetAllTexturesInFolder(url))
                    {
                        string name = icon.name.Substring(icon.name.LastIndexOf('/') + 1);
                        bodyIcons[name] = icon.texture;
                        Debug.Log("WaypointManager: Loaded icon for " + name + ".");
                    }
                }
                catch (Exception e)
                {
                    Debug.LogError("WaypointManager: Exception when attempting to load Celestial Body configuration:");
                    Debug.LogException(e);
                }
            }

            // Get all the directories for icons
            ConfigNode[] iconConfig = GameDatabase.Instance.GetConfigNodes("WAYPOINT_MANAGER_ICONS");
            foreach (ConfigNode configNode in iconConfig)
            {
                string dir = configNode.GetValue("url");
                Debug.Log("handling dir = " + dir);

                // The FinePrint logic is such that it will only look in Squad/Contracts/Icons for icons.
                // Cheat this by hacking the path in the game database.
                foreach (GameDatabase.TextureInfo texInfo in GameDatabase.Instance.databaseTexture.Where(t => t.name.StartsWith(dir)))
                {
                    Debug.Log("handling text = " + texInfo.name);
                    texInfo.name = "Squad/Contracts/Icons/" + texInfo.name;
                }
            }

            // Extra stuff!
            GameDatabase.TextureInfo nyan = GameDatabase.Instance.databaseTexture.Where(t => t.name.Contains("WaypointManager/icons/Special/nyan")).FirstOrDefault();
            if (nyan != null && DateTime.Now.Month == 4 && DateTime.Now.Day == 1)
            {
                Debug.Log("doing stuff, nyan = " + nyan.name);
                foreach (GameDatabase.TextureInfo texInfo in GameDatabase.Instance.databaseTexture.Where(t => t.name.StartsWith("Squad/Contracts/Icons/")))
                {
                    string name = texInfo.name.Replace("Squad/Contracts/Icons/", "");
                    if (!CustomWaypointGUI.forbiddenIcons.Contains(name))
                    {
                        texInfo.texture = nyan.texture;
                    }
                }
            }
        }
        
        private void ToggleWindow()
        {
            showGUI = !showGUI;
            if (!showGUI)
            {
                Config.Save();
            }<commit_msg>Removed debug message.<commit_after>﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEngine;
using KSP;
using Contracts;
using FinePrint;
using FinePrint.Utilities;

namespace WaypointManager
{
    [KSPAddon(KSPAddon.Startup.SpaceCentre, true)]
    class WaypointManager : MonoBehaviour
    {
        private const float GUI_WIDTH = 360;
        private const float SETTINGS_WIDTH = 280;

        public static WaypointManager Instance;

        private ApplicationLauncherButton launcherButton = null;
        private IButton toolbarButton;

        private bool initialized = false;
        public bool showGUI = false;
        private bool showSettings = false;
        public bool visible = true;
        private bool stylesSetup = false;

        private GUIStyle headerButtonStyle;
        private GUIStyle labelStyle;
        private GUIStyle headingStyle;
        private GUIStyle tipStyle;

        private Vector2 scrollPosition;
        private Rect settingsPosition;

        private Rect tooltipPosition;
        private List<string> toolTip = new List<string>();
        private List<double> toolTipTime = new List<double>();

        static Dictionary<string, Texture2D> bodyIcons = new Dictionary<string, Texture2D>();
        static Dictionary<CelestialBody, bool> hiddenBodies = new Dictionary<CelestialBody, bool>();

        void Start()
        {
            DontDestroyOnLoad(this);

            if (!initialized)
            {
                LoadTextures();
                LoadConfiguration();
                LoadToolbar();

                GameEvents.onGUIApplicationLauncherReady.Add(new EventVoid.OnEvent(SetupToolbar));
                GameEvents.onGUIApplicationLauncherUnreadifying.Add(new EventData<GameScenes>.OnEvent(TeardownToolbar));
                GameEvents.onGameSceneLoadRequested.Add(new EventData<GameScenes>.OnEvent(OnGameSceneLoad));
                GameEvents.onHideUI.Add(new EventVoid.OnEvent(OnHideUI));
                GameEvents.onShowUI.Add(new EventVoid.OnEvent(OnShowUI));
                GameEvents.onPlanetariumTargetChanged.Add(new EventData<MapObject>.OnEvent(PlanetariumTargetChanged));

                Config.Load();

                Instance = this;
                initialized = true;
            }
        }

        void OnDestroy()
        {
            GameEvents.onGUIApplicationLauncherReady.Remove(new EventVoid.OnEvent(SetupToolbar));
            GameEvents.onGUIApplicationLauncherUnreadifying.Remove(new EventData<GameScenes>.OnEvent(TeardownToolbar));
            GameEvents.onHideUI.Remove(OnHideUI);
            GameEvents.onShowUI.Remove(OnShowUI);
            GameEvents.onPlanetariumTargetChanged.Remove(new EventData<MapObject>.OnEvent(PlanetariumTargetChanged));

            UnloadToolbar();

            Config.Save();
        }

        private void LoadTextures()
        {
            Config.toolbarIcon = GameDatabase.Instance.GetTexture("WaypointManager/icons/toolbar", false);
            Config.addWaypointIcon = GameDatabase.Instance.GetTexture("WaypointManager/icons/addWaypoint", false);
            Config.editWaypointIcon = GameDatabase.Instance.GetTexture("WaypointManager/icons/editWaypoint", false);
            Config.deleteWaypointIcon = GameDatabase.Instance.GetTexture("WaypointManager/icons/deleteWaypoint", false);
            Config.settingsIcon = GameDatabase.Instance.GetTexture("WaypointManager/icons/settings", false);
            Config.closeIcon = GameDatabase.Instance.GetTexture("WaypointManager/icons/close", false);
        }

        private void SetupToolbar()
        {
            if (launcherButton == null && Config.useStockToolbar)
            {
                ApplicationLauncher.AppScenes visibleScenes = ApplicationLauncher.AppScenes.FLIGHT |
                    ApplicationLauncher.AppScenes.MAPVIEW |
                    ApplicationLauncher.AppScenes.TRACKSTATION;
                launcherButton = ApplicationLauncher.Instance.AddModApplication(ToggleWindow, ToggleWindow, null, null, null, null,
                    visibleScenes, Config.toolbarIcon);
            }
        }

        private void TeardownToolbar(GameScenes scene)
        {
            if (launcherButton != null)
            {
                ApplicationLauncher.Instance.RemoveModApplication(launcherButton);
                launcherButton = null;
            }
        }

        private void LoadToolbar()
        {
            if (ToolbarManager.ToolbarAvailable)
            {
                toolbarButton = ToolbarManager.Instance.add("WaypointManager", "button");
                toolbarButton.TexturePath = "WaypointManager/icons/toolbarSmall";
                toolbarButton.ToolTip = "Waypoint Manager";
                toolbarButton.Visibility = new GameScenesVisibility(GameScenes.FLIGHT, GameScenes.TRACKSTATION);
                toolbarButton.OnClick += (e) =>
                {
                    ToggleWindow();
                };
            }
        }

        private void UnloadToolbar()
        {
            toolbarButton.Destroy();
            toolbarButton = null;
        }

        private void OnGameSceneLoad(GameScenes scene)
        {
            if (scene != GameScenes.FLIGHT && scene != GameScenes.TRACKSTATION)
            {
                showGUI = false;
                showSettings = false;
                Config.Save();
            }
        }

        private void PlanetariumTargetChanged(MapObject mapObject)
        {
            CustomWaypointGUI.MapObject = mapObject;
        }

        /// <summary>
        /// Loads external config node data.
        /// </summary>
        void LoadConfiguration()
        {
            // Load all the celestial body configuration
            ConfigNode[] bodyConfig = GameDatabase.Instance.GetConfigNodes("WAYPOINT_MANAGER_BODIES");
            foreach (ConfigNode configNode in bodyConfig)
            {
                try
                {
                    string config = configNode.GetValue("name");

                    Debug.Log("WaypointManager: Loading " + config +" icons.");
                    string url = configNode.GetValue("url");
                    if (url.Last() != '/')
                    {
                        url += '/';
                    }
                    foreach (GameDatabase.TextureInfo icon in GameDatabase.Instance.GetAllTexturesInFolder(url))
                    {
                        string name = icon.name.Substring(icon.name.LastIndexOf('/') + 1);
                        bodyIcons[name] = icon.texture;
                        Debug.Log("WaypointManager: Loaded icon for " + name + ".");
                    }
                }
                catch (Exception e)
                {
                    Debug.LogError("WaypointManager: Exception when attempting to load Celestial Body configuration:");
                    Debug.LogException(e);
                }
            }

            // Get all the directories for icons
            ConfigNode[] iconConfig = GameDatabase.Instance.GetConfigNodes("WAYPOINT_MANAGER_ICONS");
            foreach (ConfigNode configNode in iconConfig)
            {
                string dir = configNode.GetValue("url");
                Debug.Log("handling dir = " + dir);

                // The FinePrint logic is such that it will only look in Squad/Contracts/Icons for icons.
                // Cheat this by hacking the path in the game database.
                foreach (GameDatabase.TextureInfo texInfo in GameDatabase.Instance.databaseTexture.Where(t => t.name.StartsWith(dir)))
                {
                    Debug.Log("handling text = " + texInfo.name);
                    texInfo.name = "Squad/Contracts/Icons/" + texInfo.name;
                }
            }

            // Extra stuff!
            GameDatabase.TextureInfo nyan = GameDatabase.Instance.databaseTexture.Where(t => t.name.Contains("WaypointManager/icons/Special/nyan")).FirstOrDefault();
            if (nyan != null && DateTime.Now.Month == 4 && DateTime.Now.Day == 1)
            {
                foreach (GameDatabase.TextureInfo texInfo in GameDatabase.Instance.databaseTexture.Where(t => t.name.StartsWith("Squad/Contracts/Icons/")))
                {
                    string name = texInfo.name.Replace("Squad/Contracts/Icons/", "");
                    if (!CustomWaypointGUI.forbiddenIcons.Contains(name))
                    {
                        texInfo.texture = nyan.texture;
                    }
                }
            }
        }
        
        private void ToggleWindow()
        {
            showGUI = !showGUI;
            if (!showGUI)
            {
                Config.Save();
            }
{'fraction_non_alphanumeric': 0.0876645483431684, 'fraction_numerical': 0.0013617793917385383, 'mean_word_length': 1.841367080444946, 'pattern_counts': {'":': 0, '<': 33, '<?xml version=': 0, '>': 41, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2260732', 'n_tokens_mistral': 4483, 'n_tokens_neox': 4223, 'n_words': 818}