using Client.Helpers;
using Client.ISServiceRef;
using Client.View;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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 AddRoleViewModel : ViewModelBase
    {
        public EmployeeDto SelectedEmployee { get; set; }
        public RoleDto SelectedRole { get; set; }
        public int SelectedRoleId { get; set; }
        public ICommand CancelCommand { get; set; }

        public ICommand AddRoleCommand { get; set; }

        public IEnumerable<RoleDto> RolesComboDataSet { get; set; }

        public AddRoleViewModel(EmployeeDto selectedEmployee)
        {
            #region clientSetup
            _roleServiceClient.ClientCredentials.UserName.UserName = UserManager.Instance.CurrentUser.Login;
            _roleServiceClient.ClientCredentials.UserName.Password = UserManager.Instance.CurrentUser.Password;
            _roleServiceClient.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;

            _userServiceClient.ClientCredentials.UserName.UserName = UserManager.Instance.CurrentUser.Login;
            _userServiceClient.ClientCredentials.UserName.Password = UserManager.Instance.CurrentUser.Password;
            _userServiceClient.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
            #endregion clientSetup

            SelectedEmployee = selectedEmployee;
            CancelCommand = new RelayCommand<IClosable>(CloseWindow);
            AddRoleCommand = new AsyncCommand<IClosable>(AddRoleAsync);

            Task.Run(async () =>
            {
                RolesComboDataSet = await _roleServiceClient.GetRolesAsync(null);
                SelectedRole = RolesComboDataSet.FirstOrDefault();
                SelectedRoleId = SelectedRole.Id;
            });
        }

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

        private async Task AddRoleAsync(IClosable window)
        {
            var user = await _userServiceClient.GetUserByIdAsync(SelectedEmployee.Id);

            var roles = user.UserRoles;

            if (!roles.Any(x => x.Identificator == SelectedRole.Identificator))
            {
                roles.Add(SelectedRole);

                var roleIds = roles.Select(x => x.Id).ToList();
                await _userServiceClient.UpdateUserWithRolesAsync(user, roleIds);

                window.Close();
            }

        }

        UserServiceClient _userServiceClient = new UserServiceClient();
        RoleServiceClient _roleServiceClient = new RoleServiceClient();
    }
}
