<commit_before>﻿using KugelmatikControl.PingPong;
using KugelmatikLibrary;
using KugelmatikLibrary.Script;
using System;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace KugelmatikControl
{
    public partial class MainForm : Form
    {
        public const string ConfigFile = "config.txt";
        public const string ClusterConfigFile = "cluster.txt";

        public Kugelmatik Kugelmatik { get; private set; }

        private ChoreographyManager choreography;

        private ClusterControl[] clusterControls;

        private LogForm logForm;
        private ConfigForm configForm;
        private ClusterForm clusterForm;
        private PingPongForm pingPongForm;
        private HeightViewForm heightViewForm;

        public MainForm()
        {
            InitializeComponent();

            Log.AutomaticFlush = false;
            Log.WriteToConsole = false;
            Log.WriteToDebug = false;

            LoadKugelmatik();
        }

        private void CloseAllWindows()
        {
            CloseWindow(logForm);
            CloseWindow(configForm);
            CloseWindow(clusterForm);
            CloseWindow(pingPongForm);
            CloseWindow(heightViewForm);
        }

        private void CloseWindow(Form form)
        {
            if (form != null && form.Visible)
                form.Close();
        }

        private void LoadKugelmatik()
        {
            try
            {
                loadError.Visible = false;
                reloadKugelmatik.Visible = false;

                CloseAllWindows();

                if (choreography != null)
                {
                    if (choreography.IsRunning)
                        choreography.Stop();
                    choreography.Dispose();
                    choreography = null;
                }
                if (Kugelmatik != null)
                    Kugelmatik.Dispose();

                Log.Info("Loading kugelmatik...");

                // Config kopieren oder laden
                Config config;
                ClusterConfig clusterConfig;

                if (Kugelmatik != null)
                {
                    config = Kugelmatik.Config;
                    clusterConfig = Kugelmatik.ClusterConfig;
                }
                else
                {
                    config = LoadOrDefault(ConfigFile, Config.GetDefault());
                    clusterConfig = LoadOrDefault(ClusterConfigFile, ClusterConfig.GetDefault());
                }

                Kugelmatik = new Kugelmatik(config, clusterConfig);

                // UI erstellen
                clustersPanel.Controls.Clear();
                clusterControls = new ClusterControl[Kugelmatik.Config.KugelmatikWidth * Kugelmatik.Config.KugelmatikHeight];

                const int padding = 5;
                for (int y = 0; y < Kugelmatik.Config.KugelmatikHeight; y++)
                    for (int x = 0; x < Kugelmatik.Config.KugelmatikWidth; x++)
                    {
                        ClusterControl cluster = new ClusterControl(Kugelmatik.GetClusterByPosition(x, Kugelmatik.Config.KugelmatikHeight - 1 - y));
                        cluster.Location = new Point(x * (cluster.Width + padding), y * (cluster.Height + padding));
                        cluster.Click += Cluster_Click;
                        clustersPanel.Controls.Add(cluster);
                        clusterControls[y * Kugelmatik.Config.KugelmatikWidth + x] = cluster;
                    }
            }
            catch(Exception e)
            {
                Log.Error(e);
                MessageBox.Show(e.ToString(), "Could not load kugelmatik", MessageBoxButtons.OK, MessageBoxIcon.Error);

                loadError.Visible = true;
                reloadKugelmatik.Visible = true;

                clusterControls = new ClusterControl[0];
            }

            UpdateNetworkStatus();
            UpdateChoreographyStatus();
        }

        private static T LoadOrDefault<T>(string file, T defaultValue)
        {
            if (File.Exists(file))
                return ConfigHelper.LoadConfigFromFile(file, defaultValue);

            ConfigHelper.SaveToFile(file, defaultValue);
            return defaultValue;
        }

        protected override void OnClosed(EventArgs e)
        {
            StopChoreographyInternal();

            if (Kugelmatik != null)
                Kugelmatik.Dispose();

            base.OnClosed(e);
        }

        private int tickCount = 0;

        private void updateTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                if (Kugelmatik == null)
                    return;

                // Ping senden
                Kugelmatik.SendPing();

                // Daten senden
                if (!viewOnlyToolStripMenuItem.Checked)
                {
                    // alle 8 Ticks werden die Daten vollständig gesendet<commit_msg>Prüfen ob schon Kugelmatik Instanzen schon laufen<commit_after>﻿using KugelmatikControl.PingPong;
using KugelmatikLibrary;
using KugelmatikLibrary.Script;
using System;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace KugelmatikControl
{
    public partial class MainForm : Form
    {
        public const string ConfigFile = "config.txt";
        public const string ClusterConfigFile = "cluster.txt";

        public Kugelmatik Kugelmatik { get; private set; }

        private ChoreographyManager choreography;

        private ClusterControl[] clusterControls;

        private LogForm logForm;
        private ConfigForm configForm;
        private ClusterForm clusterForm;
        private PingPongForm pingPongForm;
        private HeightViewForm heightViewForm;

        public MainForm()
        {
            InitializeComponent();

            Log.AutomaticFlush = false;
            Log.WriteToConsole = false;
            Log.WriteToDebug = false;

            LoadKugelmatik();
        }

        private void CloseAllWindows()
        {
            CloseWindow(logForm);
            CloseWindow(configForm);
            CloseWindow(clusterForm);
            CloseWindow(pingPongForm);
            CloseWindow(heightViewForm);
        }

        private void CloseWindow(Form form)
        {
            if (form != null && form.Visible)
                form.Close();
        }

        private void LoadKugelmatik()
        {
            try
            {
                loadError.Visible = false;
                reloadKugelmatik.Visible = false;

                UnloadKugelmatik();

                Log.Info("Loading kugelmatik...");

                CheckOtherInstances();

                // Config kopieren oder laden
                Config config;
                ClusterConfig clusterConfig;

                if (Kugelmatik != null)
                {
                    config = Kugelmatik.Config;
                    clusterConfig = Kugelmatik.ClusterConfig;
                }
                else
                {
                    config = LoadOrDefault(ConfigFile, Config.GetDefault());
                    clusterConfig = LoadOrDefault(ClusterConfigFile, ClusterConfig.GetDefault());
                }

                Kugelmatik = new Kugelmatik(config, clusterConfig);

                // UI erstellen
                clustersPanel.Controls.Clear();
                clusterControls = new ClusterControl[Kugelmatik.Config.KugelmatikWidth * Kugelmatik.Config.KugelmatikHeight];

                const int padding = 5;
                for (int y = 0; y < Kugelmatik.Config.KugelmatikHeight; y++)
                    for (int x = 0; x < Kugelmatik.Config.KugelmatikWidth; x++)
                    {
                        ClusterControl cluster = new ClusterControl(Kugelmatik.GetClusterByPosition(x, Kugelmatik.Config.KugelmatikHeight - 1 - y));
                        cluster.Location = new Point(x * (cluster.Width + padding), y * (cluster.Height + padding));
                        cluster.Click += Cluster_Click;
                        clustersPanel.Controls.Add(cluster);
                        clusterControls[y * Kugelmatik.Config.KugelmatikWidth + x] = cluster;
                    }
            }
            catch(Exception e)
            {
                Log.Error(e);
                MessageBox.Show(e.ToString(), "Could not load kugelmatik", MessageBoxButtons.OK, MessageBoxIcon.Error);

                loadError.Visible = true;
                reloadKugelmatik.Visible = true;

                clusterControls = new ClusterControl[0];
            }

            UpdateNetworkStatus();
            UpdateChoreographyStatus();
        }

        

        private void CheckOtherInstances()
        {
            DialogResult result;
            do
            {
                Process self = Process.GetCurrentProcess();
                Process[] processes = Process.GetProcessesByName(self.ProcessName);
                if (processes.Length <= 1)
                    return;

                string text = "Following instances found:";
                text += Environment.NewLine;
                text += string.Join(Environment.NewLine,
                    processes.Where(p => p.Id != self.Id).Select(p => string.Format("{0} (PID {1})", p.ProcessName, p.Id)));

                result = MessageBox.Show(text, "Multiple Kugelmatik instances running",
                    MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);

                if (result == DialogResult.Ignore)
                    return;

                if (result == DialogResult.Abort)
                    throw new InvalidOperationException("A Kugelmatik instance is already running");
            }
            while (result == DialogResult.Retry);
        }

        private static T LoadOrDefault<T>(string file, T defaultValue)
        {
            if (File.Exists(file))
                return ConfigHelper.LoadConfigFromFile(file, defaultValue);

            ConfigHelper.SaveToFile(file, defaultValue);
            return defaultValue;
        }

        private void UnloadKugelmatik()
        {
            CloseAllWindows();
            StopChoreographyInternal();

            if (Kugelmatik != null)
                Kugelmatik.Dispose();
        }

        protected override void OnClosed(EventArgs e)
        {
            UnloadKugelmatik();
            base.OnClosed(e);
        }

        private int tickCount = 0;

        private void updateTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                if (Kugelmatik == null)
                    return;

                // Ping senden
                Kugelmatik.SendPing();

                // Daten senden
                if (!viewOnlyToolStripMenuItem.Checked)
                {
                    // alle 8 Ticks werden die Daten vollständig gesendet
{'fraction_non_alphanumeric': 0.07817055393586006, 'fraction_numerical': 0.0015488338192419825, 'mean_word_length': 1.5067366978762275, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 7, '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': '4712413', 'n_tokens_mistral': 2894, 'n_tokens_neox': 2688, 'n_words': 583}