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 EmployeeDetailViewModel : ViewModelBase
    {

        public EmployeeDto Employee { get; set; }
        public ICommand CancelCommand { get; set; }

        public ICommand SaveEmployeeCommand { get; set; }

        public IEnumerable<EmployeePositionDto> PositionComboDataSet { get; set; }
        public IEnumerable<DepartmentDto> DepartmentComboDataSet { get; set; }

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

            _employeePositionServiceClient.ClientCredentials.UserName.UserName = UserManager.Instance.CurrentUser.Login;
            _employeePositionServiceClient.ClientCredentials.UserName.Password = UserManager.Instance.CurrentUser.Password;
            _employeePositionServiceClient.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;

            _departmentServiceClient.ClientCredentials.UserName.UserName = UserManager.Instance.CurrentUser.Login;
            _departmentServiceClient.ClientCredentials.UserName.Password = UserManager.Instance.CurrentUser.Password;
            _departmentServiceClient.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;

            _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;
            #endregion clientSetup

            Employee = employee;
            CancelCommand = new RelayCommand<IClosable>(CloseWindow);
            SaveEmployeeCommand = new AsyncCommand<IClosable>(SaveEmployeeAsync);

            Task.Run(async () =>
            {
                PositionComboDataSet = await _employeePositionServiceClient.GetEmployeePositionsAsync(null);
                if (Employee.EmployeePosition == null)
                {
                    var position = PositionComboDataSet.FirstOrDefault();
                    Employee.EmployeePosition = position;
                    Employee.EmployeePositionId = position.Id;
                }
            });
            Task.Run(async () =>
            {
                DepartmentComboDataSet = await _departmentServiceClient.GetDepartmentsAsync(null);
                if (Employee.Department == null)
                {
                    var department = DepartmentComboDataSet.FirstOrDefault();
                    Employee.Department = department;
                    Employee.DepartmentId = department.Id;
                }
            });
        }

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

        private async Task SaveEmployeeAsync(IClosable window)
        {
            var employee = await _employeeServiceClient.GetEmployeeByIdAsync(Employee.Id);

            if (employee != null)
            {
                await _employeeServiceClient.UpdateEmployeeAsync(Employee);
            }
            else
            {
                var random = new Random();

                byte[] tempBytes;
                tempBytes = Encoding.GetEncoding("ISO-8859-8").GetBytes($"{Employee.LastName.ToLower()}{Employee.FirstName.ToLower().First()}{random.Next(1,99)}");
                string login = Encoding.UTF8.GetString(tempBytes);
                string password = $"PadoKufox{random.Next(100, 300)}";

                var userDto = new UserDto()
                {
                    Employee = Employee,
                    Login = login,
                    Password = password
                };

                

                await _employeeServiceClient.CreateEmployeeAsync(Employee);

                var filter = new FilterDto()
                {
                    Conditions = new List<ConditionItemDto>()
                     {
                          new ConditionItemDto()
                          {
                               Column = nameof(EmployeeDto.NationalId),
                               Type = ConditionTypeEnum.Equal,
                               Value = Employee.NationalId
                          }
                     }
                };

                var createdEmployee = (await _employeeServiceClient.GetEmployeesAsync(filter)).FirstOrDefault();

                userDto.Id = createdEmployee.Id;
                await _userServiceClient.CreateUserAsync(userDto);


                var roleFilter = new FilterDto()
                {
                    Conditions = new List<ConditionItemDto>()
                     {
                          new ConditionItemDto()
                          {
                               Column = nameof(RoleDto.Identificator),
                               Type = ConditionTypeEnum.Equal,
                               Value = "BASIC_ACCESS"
                          }
                     }
                };

                var basicRole = (await _roleServiceClient.GetRolesAsync(roleFilter)).FirstOrDefault();

                await _userServiceClient.UpdateUserWithRolesAsync(userDto, new List<int>(){ basicRole.Id });
              

                Xceed.Wpf.Toolkit.MessageBox.Show(String.Format(Properties.Resources.UserCreated, login, password), string.Empty, MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }

            window.Close();
        }

        EmployeeServiceClient _employeeServiceClient = new EmployeeServiceClient();
        EmployeePositionServiceClient _employeePositionServiceClient = new EmployeePositionServiceClient();
        DepartmentServiceClient _departmentServiceClient = new DepartmentServiceClient();
        UserServiceClient _userServiceClient = new UserServiceClient();
        RoleServiceClient _roleServiceClient = new RoleServiceClient();
    }
}
