<commit_before>﻿using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Certify.Locales;
using Certify.Models;
using Certify.UI.Settings;
using Microsoft.ApplicationInsights;

namespace Certify.UI
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        public enum PrimaryUITabs
        {
            ManagedCertificates = 0,

            CurrentProgress = 1
        }

        private TelemetryClient tc = null;

        protected Certify.UI.ViewModel.AppViewModel _appViewModel => UI.ViewModel.AppViewModel.Current;
        protected Certify.UI.ViewModel.ManagedCertificateViewModel _itemViewModel => UI.ViewModel.ManagedCertificateViewModel.Current;
        private const int NUM_ITEMS_FOR_REMINDER = 3;
        private const int NUM_ITEMS_FOR_LIMIT = 5;

        public int NumManagedCertificates
        {
            get
            {
                if (_appViewModel != null && _appViewModel.ManagedCertificates != null)
                {
                    return _appViewModel.ManagedCertificates.Count;
                }
                else
                {
                    return 0;
                }
            }
        }

        public MainWindow()
        {
            InitializeComponent();
            DataContext = _appViewModel;

            this.Activate();
        }

        private async void Button_NewCertificate(object sender, RoutedEventArgs e)
        {
#if ALPHA
            MessageBox.Show("You are using an alpha version of Certify The Web. You should only use this version for testing and should not consider it suitable for use on production servers.");
#endif

#if BETA
            MessageBox.Show("You are using a beta version of Certify The Web. Please report any issues you find.");
#endif

            // save or discard site changes before creating a new site/certificate
            if (!await _itemViewModel.ConfirmDiscardUnsavedChanges())
            {
                return;
            }

            var managedCertCount = _appViewModel.ManagedCertificates?.Where(c => string.IsNullOrEmpty(c.SourceId)).Count() ?? 0;

            if (!_appViewModel.IsRegisteredVersion && managedCertCount >= NUM_ITEMS_FOR_REMINDER)
            {
                MessageBox.Show(SR.MainWindow_TrialLimitationReached);

                if (managedCertCount >= NUM_ITEMS_FOR_LIMIT)
                {
                    return;
                }
            }
            else
            {
                if (_appViewModel.IsRegisteredVersion && managedCertCount >= 1)
                {
                    var licensingManager = ViewModel.AppViewModel.Current.PluginManager?.LicensingManager;

                    if (licensingManager != null && !await licensingManager.IsInstallActive(ViewModel.AppViewModel.ProductTypeId, Management.Util.GetAppDataFolder()))
                    {
                        MessageBox.Show(Certify.Locales.SR.MainWindow_KeyExpired);

                        if (managedCertCount >= NUM_ITEMS_FOR_LIMIT)
                        {
                            return;
                        }
                    }
                }
            }

            // check user has registered a contact with LE first
            if (!_appViewModel.HasRegisteredContacts)
            {
                EnsureContactRegistered();
                return;
            }

            //present new managed item (certificate request) UI
            //select tab Managed Items
            _appViewModel.MainUITabIndex = (int)PrimaryUITabs.ManagedCertificates;

            _appViewModel.SelectedItem = null; // deselect site list item
            _appViewModel.SelectedItem = new Certify.Models.ManagedCertificate();

            //default to auto deploy for new managed certs
            _appViewModel.SelectedItem.RequestConfig.DeploymentSiteOption = Models.DeploymentOption.Auto;
        }

        private async void Button_RenewAll(object sender, RoutedEventArgs e)
        {
            var settings = new Models.RenewalSettings { };

            // if ctrl is pressed, force renewal
            if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
            {
                settings.Mode = Models.RenewalMode.All;
            }

            // save or discard site changes before creating a new site/certificate
            if (!await _itemViewModel.ConfirmDiscardUnsavedChanges())
            {
                return;
            }

            //present new renew all confirmation
            if (MessageBox.Show(SR.MainWindow_RenewAllConfirm, SR.Renew_All, MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                _appViewModel.MainUITabIndex = (int)PrimaryUITabs.CurrentProgress;

                // renewals is a long running process so we need to run renewals process in the
                // background and present UI to show progress.
                // TODO: We should prevent starting the renewals process if it is currently in progress.
                if (_appViewModel.RenewAllCommand.CanExecute(settings))
                {
                    _appViewModel.RenewAllCommand.Execute(settings);
                }
            }
        }

        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var uiSettings = UISettings.Load();

            if (uiSettings != null)
            {
                Width = uiSettings.Width ?? Width;
                Height = uiSettings.Height ?? Height;

                Top = uiSettings.Top ?? Top;

                // only apply saved left pos if it's not off-screen
                double virtScreenWidth = System.Windows.SystemParameters.VirtualScreenWidth;
                if (uiSettings.Left < virtScreenWidth)
                {
                    Left = uiSettings.Left ?? Left;
                }

                // set theme based on pref
                if (uiSettings.UITheme != null)
                {
                    ((Certify.UI.App)App.Current).ToggleTheme(uiSettings.UITheme);
                }
                else
                {
                    // default theme
                    ((Certify.UI.App)App.Current).ToggleTheme(_appViewModel.DefaultUITheme);
                }

                if (uiSettings.Scaling > 0.5 && uiSettings.Scaling < 2)
                {
                    _appViewModel.UIScaleFactor = uiSettings.Scaling ?? 1;
                }

                _appViewModel.UISettings = uiSettings;
            }
            else
            {
                // default theme
                ((Certify.UI.App)App.Current).ToggleTheme(_appViewModel.DefaultUITheme);
            }

            await PerformAppStartupChecks();


        }


        private async Task PerformAppStartupChecks()
        {
            Mouse.OverrideCursor = Cursors.AppStarting;
            _appViewModel.IsLoading = true;



            var cts = new CancellationTokenSource();<commit_msg>Catch exception if window position unavailable<commit_after>﻿using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Certify.Locales;
using Certify.Models;
using Certify.UI.Settings;
using Microsoft.ApplicationInsights;

namespace Certify.UI
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        public enum PrimaryUITabs
        {
            ManagedCertificates = 0,

            CurrentProgress = 1
        }

        private TelemetryClient tc = null;

        protected Certify.UI.ViewModel.AppViewModel _appViewModel => UI.ViewModel.AppViewModel.Current;
        protected Certify.UI.ViewModel.ManagedCertificateViewModel _itemViewModel => UI.ViewModel.ManagedCertificateViewModel.Current;
        private const int NUM_ITEMS_FOR_REMINDER = 3;
        private const int NUM_ITEMS_FOR_LIMIT = 5;

        public int NumManagedCertificates
        {
            get
            {
                if (_appViewModel != null && _appViewModel.ManagedCertificates != null)
                {
                    return _appViewModel.ManagedCertificates.Count;
                }
                else
                {
                    return 0;
                }
            }
        }

        public MainWindow()
        {
            InitializeComponent();
            DataContext = _appViewModel;

            this.Activate();
        }

        private async void Button_NewCertificate(object sender, RoutedEventArgs e)
        {
#if ALPHA
            MessageBox.Show("You are using an alpha version of Certify The Web. You should only use this version for testing and should not consider it suitable for use on production servers.");
#endif

#if BETA
            MessageBox.Show("You are using a beta version of Certify The Web. Please report any issues you find.");
#endif

            // save or discard site changes before creating a new site/certificate
            if (!await _itemViewModel.ConfirmDiscardUnsavedChanges())
            {
                return;
            }

            var managedCertCount = _appViewModel.ManagedCertificates?.Where(c => string.IsNullOrEmpty(c.SourceId)).Count() ?? 0;

            if (!_appViewModel.IsRegisteredVersion && managedCertCount >= NUM_ITEMS_FOR_REMINDER)
            {
                MessageBox.Show(SR.MainWindow_TrialLimitationReached);

                if (managedCertCount >= NUM_ITEMS_FOR_LIMIT)
                {
                    return;
                }
            }
            else
            {
                if (_appViewModel.IsRegisteredVersion && managedCertCount >= 1)
                {
                    var licensingManager = ViewModel.AppViewModel.Current.PluginManager?.LicensingManager;

                    if (licensingManager != null && !await licensingManager.IsInstallActive(ViewModel.AppViewModel.ProductTypeId, Management.Util.GetAppDataFolder()))
                    {
                        MessageBox.Show(Certify.Locales.SR.MainWindow_KeyExpired);

                        if (managedCertCount >= NUM_ITEMS_FOR_LIMIT)
                        {
                            return;
                        }
                    }
                }
            }

            // check user has registered a contact with LE first
            if (!_appViewModel.HasRegisteredContacts)
            {
                EnsureContactRegistered();
                return;
            }

            //present new managed item (certificate request) UI
            //select tab Managed Items
            _appViewModel.MainUITabIndex = (int)PrimaryUITabs.ManagedCertificates;

            _appViewModel.SelectedItem = null; // deselect site list item
            _appViewModel.SelectedItem = new Certify.Models.ManagedCertificate();

            //default to auto deploy for new managed certs
            _appViewModel.SelectedItem.RequestConfig.DeploymentSiteOption = Models.DeploymentOption.Auto;
        }

        private async void Button_RenewAll(object sender, RoutedEventArgs e)
        {
            var settings = new Models.RenewalSettings { };

            // if ctrl is pressed, force renewal
            if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
            {
                settings.Mode = Models.RenewalMode.All;
            }

            // save or discard site changes before creating a new site/certificate
            if (!await _itemViewModel.ConfirmDiscardUnsavedChanges())
            {
                return;
            }

            //present new renew all confirmation
            if (MessageBox.Show(SR.MainWindow_RenewAllConfirm, SR.Renew_All, MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                _appViewModel.MainUITabIndex = (int)PrimaryUITabs.CurrentProgress;

                // renewals is a long running process so we need to run renewals process in the
                // background and present UI to show progress.
                // TODO: We should prevent starting the renewals process if it is currently in progress.
                if (_appViewModel.RenewAllCommand.CanExecute(settings))
                {
                    _appViewModel.RenewAllCommand.Execute(settings);
                }
            }
        }

        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var uiSettings = UISettings.Load();

            if (uiSettings != null)
            {
                try
                {
                    Width = uiSettings.Width ?? Width;
                    Height = uiSettings.Height ?? Height;

                    Top = uiSettings.Top ?? Top;

                    // only apply saved left pos if it's not off-screen
                    double virtScreenWidth = System.Windows.SystemParameters.VirtualScreenWidth;
                    if (uiSettings.Left < virtScreenWidth)
                    {
                        Left = uiSettings.Left ?? Left;
                    }

                    // set theme based on pref
                    if (uiSettings.UITheme != null)
                    {
                        ((Certify.UI.App)App.Current).ToggleTheme(uiSettings.UITheme);
                    }
                    else
                    {
                        // default theme
                        ((Certify.UI.App)App.Current).ToggleTheme(_appViewModel.DefaultUITheme);
                    }

                    if (uiSettings.Scaling > 0.5 && uiSettings.Scaling < 2)
                    {
                        _appViewModel.UIScaleFactor = uiSettings.Scaling ?? 1;
                    }

                    _appViewModel.UISettings = uiSettings;
                }
                catch
                {
                    // failed to get window position etc
                }
            }
            else
            {
                // default theme
                ((Certify.UI.App)App.Current).ToggleTheme(_appViewModel.DefaultUITheme);
            }

            await PerformAppStartupChecks();


        }


        private async Task PerformAppStartupChecks()
        {
            Mouse.OverrideCursor = Cursors.AppStarting;
            _appViewModel.IsLoading = true;



            var cts = new CancellationTokenSource();
{'fraction_non_alphanumeric': 0.07099697885196375, 'fraction_numerical': 0.0015105740181268882, 'mean_word_length': 1.5370144574116007, 'pattern_counts': {'":': 0, '<': 11, '<?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': '3377733', 'n_tokens_mistral': 3668, 'n_tokens_neox': 3325, 'n_words': 814}