using eSuite.WorkBench.Helpers;
using eSuite.WorkBench.WpfHelper;
using System;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace eSuite.WorkBench.Commands
{
    public class SaveUserSettingsCommand : AsyncCommandBase
    {
        private readonly MainWindowViewModel _mainWindowViewModel;

        public SaveUserSettingsCommand(MainWindowViewModel mainWindowViewModel, Action<Exception> onException, EventHandler<FeedbackEventArgs> addFeedbackMessage) : base(onException)
        {
            FeedbackMessage += addFeedbackMessage;
            _mainWindowViewModel = mainWindowViewModel;
        }

        protected override Task ExecuteAsync(object parameter)
        {
            PasswordBox passwordBox = parameter as PasswordBox;
            if (passwordBox == null)
            {
                throw new NullReferenceException();
            }

            using(var secureStringDecoder = new SecureStringDecoder(passwordBox.SecurePassword))
            {
                _mainWindowViewModel.SettingsPassword = secureStringDecoder.DecodeString();
            }

            Properties.Settings.Default.SqlServerAdminLogin = _mainWindowViewModel.SettingsLogin;
            if (!string.IsNullOrWhiteSpace(_mainWindowViewModel.SettingsPassword))
                Properties.Settings.Default.SqlServerAdminPassword = _mainWindowViewModel.SettingsPassword;
            Properties.Settings.Default.DeveloperMode = _mainWindowViewModel.DeveloperMode;
            Properties.Settings.Default.DevopsPersonalAccessKey = _mainWindowViewModel.DevopsPersonalAccessKey;
            Properties.Settings.Default.Save();
            DoFeedbackMessage("Settings Saved");
            return Task.CompletedTask;
        }

        public override bool CanExecute(object parameter)
        {
            if (!base.CanExecute(parameter))
                return false;

            string newPassword;

            PasswordBox passwordBox = parameter as PasswordBox;
            using (var secureStringDecoder = new SecureStringDecoder(passwordBox.SecurePassword))
            {
                newPassword = secureStringDecoder.DecodeString();
            }

            if (_mainWindowViewModel.SettingsLogin != Properties.Settings.Default.SqlServerAdminLogin)
                return true;
            if (!string.IsNullOrEmpty(newPassword) && newPassword != Properties.Settings.Default.SqlServerAdminPassword)
                return true;
            if (_mainWindowViewModel.DeveloperMode != Properties.Settings.Default.DeveloperMode)
                return true;
            if (Properties.Settings.Default.DevopsPersonalAccessKey != _mainWindowViewModel.DevopsPersonalAccessKey)
                return true;

            return false;
        }
    }
}
