using Client.Helpers;
using Client.View;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using WpfAsyncPack.Command;

namespace Client.ViewModel
{
    public class ChangePasswordViewModel : ViewModelBase
    {

        public string OldPassword { get; set; }

        public string NewPassword { get; set; }
        public string NewPasswordCheck { get; set; }
        public ICommand ChangePasswordCommand { get; set; } 
        public ICommand CancelCommand { get; set; }
        public ChangePasswordViewModel()
        {
            ChangePasswordCommand = new AsyncCommand<IClosable>(ChangePasswordAsync);
            CancelCommand = new RelayCommand<IClosable>(Cancel);
        }


        private async Task ChangePasswordAsync(IClosable window)
        {
            if (NewPassword != NewPasswordCheck)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show(Properties.Resources.NewPasswordCheckFailed, string.Empty, MessageBoxButton.OK, MessageBoxImage.Error);
            }

            var userService = new ISServiceRef.UserServiceClient();

            userService.ClientCredentials.UserName.UserName = UserManager.Instance.CurrentUser.Login;
            userService.ClientCredentials.UserName.Password = OldPassword;
            userService.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
            try
            {
                var user = await userService.LoginAsync(UserManager.Instance.CurrentUser.Login);

                user.Password = NewPassword;

                await userService.UpdateUserAsync(user);

                Xceed.Wpf.Toolkit.MessageBox.Show(Properties.Resources.PasswordChanged, string.Empty, MessageBoxButton.OK, MessageBoxImage.Information);
                window.Close();
            }
            catch
            {
                Xceed.Wpf.Toolkit.MessageBox.Show(Properties.Resources.LoginFailed, string.Empty, MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void Cancel(IClosable window)
        {
            window.Close();
        }
    }
}
