<commit_before>﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using CoolFishNS.Bots;
using CoolFishNS.Management;
using CoolFishNS.PluginSystem;
using CoolFishNS.RemoteNotification.Analytics;
using CoolFishNS.Targets;
using CoolFishNS.Utilities;
using NLog;
using NLog.Config;
using NLog.Targets.Wrappers;

namespace CoolFishNS
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        private readonly IList<IBot> _bots = new List<IBot>();
        private readonly AnalyticsManager _manager;
        private readonly ICollection<CheckBox> _pluginCheckBoxesList = new Collection<CheckBox>();
        private readonly SplashScreen _splashScreen;
        private Process[] _processes = new Process[0];


        public MainWindow(SplashScreen splashScreen)
        {
            _splashScreen = splashScreen;
            _manager = new AnalyticsManager();
            InitializeComponent();
        }

        private void UpdateControlSettings()
        {
            foreach (var plugin in PluginManager.Plugins)
            {
                var cb = new CheckBox {Content = plugin.Key};
                cb.Checked += changedCheck;
                cb.Unchecked += changedCheck;
                cb.IsChecked = UserPreferences.Default.Plugins.ContainsKey(plugin.Key) &&
                               (UserPreferences.Default.Plugins[plugin.Key].IsEnabled == true);

                _pluginCheckBoxesList.Add(cb);
            }

            LogLevelCMB.SelectedIndex = UserPreferences.Default.LogLevel;
            ScriptsLB.ItemsSource = _pluginCheckBoxesList;
        }

        private void SaveControlSettings()
        {
            foreach (CheckBox script in _pluginCheckBoxesList)
            {
                UserPreferences.Default.Plugins[script.Content.ToString()] = new SerializablePlugin
                {
                    FileName = script.Content.ToString(),
                    IsEnabled = script.IsChecked
                };
            }
            UserPreferences.Default.LogLevel = LogLevelCMB.SelectedIndex;
        }

        private void RefreshProcesses()
        {
            ProcessCB.Items.Clear();

            _processes = BotManager.GetWowProcesses();

            foreach (Process process in _processes)
            {
                try
                {
                    ProcessCB.Items.Add("Id: " + process.Id + " Name: " + process.MainWindowTitle);
                }
                catch (Exception ex)
                {
                    Logger.Trace("Error adding process", ex);
                }
            }
        }

        private void OnCloseWindow(object sender, MouseButtonEventArgs e)
        {
            _manager.SendAnalyticsEvent((DateTime.Now - Utilities.Utilities.StartTime).TotalMilliseconds, "ApplicationClose");
            Application.Current.Shutdown();
        }

        private void OnDragMoveWindow(object sender, MouseButtonEventArgs e)
        {
            try
            {
                DragMove();
            }
            catch (InvalidOperationException ex)
            {
                if (Logger.IsTraceEnabled)
                {
                    Logger.Trace("Error moving window", (Exception) ex);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Error moving window", ex);
            }
        }

        private void OnMinimizeWindow(object sender, MouseButtonEventArgs e)
        {
            WindowState = WindowState.Minimized;
        }

        private void LogLevelCMB_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                int ordinal = LogLevelCMB.SelectedIndex == -1 ? 2 : LogLevelCMB.SelectedIndex;
                Utilities.Utilities.Reconfigure(ordinal);
            }
            catch (Exception ex)
            {
                Logger.Error("Exception thrown while changing log level", ex);
            }
        }

        private void MainWindow1_ContentRendered(object sender, EventArgs e)
        {
            UpdateControlSettings();
            StartupTask();
            _splashScreen.Close(new TimeSpan(0));
        }

        private async void StartupTask()
        {
            await Task.Run(() =>
            {
                Logger.Info(Environment.NewLine + Utilities.Utilities.GetNews() + Environment.NewLine);
                Logger.Info("CoolFish Version: " + Constants.Version.Value);
                BotManager.StartUp();
                _manager.SendAnalyticsEvent(0, "ApplicationStart");
                Updater.Update();
                AutoSelectBot();
                Process[] procs = BotManager.GetWowProcesses();
                if (procs.Length == 1)
                {
                    BotManager.AttachToProcess(procs.First());
                }
            });
        }

        private void AutoSelectBot()
        {
            Dispatcher.Invoke(() =>
            {
                BotBaseCB_DropDownOpened(null, null);
                if (BotManager.LoadedBots.Any())
                {
                    BotBaseCB.SelectedIndex = 0;
                }
            });
        }

        #region EventHandlers

        private void btn_Attach_Click(object sender, EventArgs e)
        {
            if (_processes.Length > ProcessCB.SelectedIndex && ProcessCB.SelectedIndex >= 0) // return if we have an invalid process
            {
                BotManager.AttachToProcess(_processes[ProcessCB.SelectedIndex]);
            }
            else
            {
                Logger.Warn("Please pick a process to attach to.");
            }
        }

        private void ComboBox_DropDownOpened_1(object sender, EventArgs e)
        {
            try<commit_msg>Auto select first bot base if any are loaded<commit_after>﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using CoolFishNS.Bots;
using CoolFishNS.Management;
using CoolFishNS.PluginSystem;
using CoolFishNS.RemoteNotification.Analytics;
using CoolFishNS.Targets;
using CoolFishNS.Utilities;
using NLog;
using NLog.Config;
using NLog.Targets.Wrappers;

namespace CoolFishNS
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        private readonly IList<IBot> _bots = new List<IBot>();
        private readonly AnalyticsManager _manager;
        private readonly ICollection<CheckBox> _pluginCheckBoxesList = new Collection<CheckBox>();
        private readonly SplashScreen _splashScreen;
        private Process[] _processes = new Process[0];


        public MainWindow(SplashScreen splashScreen)
        {
            _splashScreen = splashScreen;
            _manager = new AnalyticsManager();
            InitializeComponent();
        }

        private void UpdateControlSettings()
        {
            foreach (var plugin in PluginManager.Plugins)
            {
                var cb = new CheckBox {Content = plugin.Key};
                cb.Checked += changedCheck;
                cb.Unchecked += changedCheck;
                cb.IsChecked = UserPreferences.Default.Plugins.ContainsKey(plugin.Key) &&
                               (UserPreferences.Default.Plugins[plugin.Key].IsEnabled == true);

                _pluginCheckBoxesList.Add(cb);
            }

            LogLevelCMB.SelectedIndex = UserPreferences.Default.LogLevel;
            ScriptsLB.ItemsSource = _pluginCheckBoxesList;
        }

        private void SaveControlSettings()
        {
            foreach (CheckBox script in _pluginCheckBoxesList)
            {
                UserPreferences.Default.Plugins[script.Content.ToString()] = new SerializablePlugin
                {
                    FileName = script.Content.ToString(),
                    IsEnabled = script.IsChecked
                };
            }
            UserPreferences.Default.LogLevel = LogLevelCMB.SelectedIndex;
        }

        private void RefreshProcesses()
        {
            ProcessCB.Items.Clear();

            _processes = BotManager.GetWowProcesses();

            foreach (Process process in _processes)
            {
                try
                {
                    ProcessCB.Items.Add("Id: " + process.Id + " Name: " + process.MainWindowTitle);
                }
                catch (Exception ex)
                {
                    Logger.Trace("Error adding process", ex);
                }
            }
        }

        private void OnCloseWindow(object sender, MouseButtonEventArgs e)
        {
            _manager.SendAnalyticsEvent((DateTime.Now - Utilities.Utilities.StartTime).TotalMilliseconds, "ApplicationClose");
            Application.Current.Shutdown();
        }

        private void OnDragMoveWindow(object sender, MouseButtonEventArgs e)
        {
            try
            {
                DragMove();
            }
            catch (InvalidOperationException ex)
            {
                if (Logger.IsTraceEnabled)
                {
                    Logger.Trace("Error moving window", (Exception) ex);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Error moving window", ex);
            }
        }

        private void OnMinimizeWindow(object sender, MouseButtonEventArgs e)
        {
            WindowState = WindowState.Minimized;
        }

        private void LogLevelCMB_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                int ordinal = LogLevelCMB.SelectedIndex == -1 ? 2 : LogLevelCMB.SelectedIndex;
                Utilities.Utilities.Reconfigure(ordinal);
            }
            catch (Exception ex)
            {
                Logger.Error("Exception thrown while changing log level", ex);
            }
        }

        private void MainWindow1_ContentRendered(object sender, EventArgs e)
        {
            UpdateControlSettings();
            StartupTask();
            _splashScreen.Close(new TimeSpan(0));
        }

        private async void StartupTask()
        {
            await Task.Run(() =>
            {
                Logger.Info(Environment.NewLine + Utilities.Utilities.GetNews() + Environment.NewLine);
                Logger.Info("CoolFish Version: " + Constants.Version.Value);
                BotManager.StartUp();
                _manager.SendAnalyticsEvent(0, "ApplicationStart");
                Updater.Update();
                AutoSelectBot();
                Process[] procs = BotManager.GetWowProcesses();
                if (procs.Length == 1)
                {
                    BotManager.AttachToProcess(procs.First());
                }
            });
        }

        private void AutoSelectBot()
        {
            Dispatcher.Invoke(() =>
            {
                BotBaseCB_DropDownOpened(null, null);
                if (BotManager.LoadedBots.Any())
                {
                    BotBaseCB.SelectedIndex = 0;
                    BotBaseCB_DropDownClosed(null, null);
                }
            });
        }

        #region EventHandlers

        private void btn_Attach_Click(object sender, EventArgs e)
        {
            if (_processes.Length > ProcessCB.SelectedIndex && ProcessCB.SelectedIndex >= 0) // return if we have an invalid process
            {
                BotManager.AttachToProcess(_processes[ProcessCB.SelectedIndex]);
            }
            else
            {
                Logger.Warn("Please pick a process to attach to.");
            }
        }

        private void ComboBox_DropDownOpened_1(object sender, EventArgs e)
        {
            try
{'fraction_non_alphanumeric': 0.08222060370640123, 'fraction_numerical': 0.0016185158209921502, 'mean_word_length': 1.6344063099552335, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 23, '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': '1670016', 'n_tokens_mistral': 3077, 'n_tokens_neox': 2914, 'n_words': 617}