using Client.Helpers;
using Client.ISServiceRef;
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;
using Xceed.Wpf.Toolkit;

namespace Client.ViewModel
{
    public class DepartmentDetailViewModel : ViewModelBase
    {

        public ICommand CancelCommand { get; set; }

        public ICommand SaveDepartmentCommand { get; set; }
        
        public DepartmentDto Department { get; set; }

        public DepartmentDetailViewModel(DepartmentDto department)
        {
            _client.ClientCredentials.UserName.UserName = UserManager.Instance.CurrentUser.Login;
            _client.ClientCredentials.UserName.Password = UserManager.Instance.CurrentUser.Password;
            _client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
            Department = department;
            SaveDepartmentCommand = new AsyncCommand<IClosable>(SaveDepartmentAsync);
            CancelCommand = new RelayCommand<IClosable>(CloseWindow);
        }

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


        private async Task SaveDepartmentAsync(IClosable window)
        {

            var department = await _client.GetDepartmentByIdAsync(Department.Id);

            try
            {
                if (department != null)
                {
                    await _client.UpdateDepartmentAsync(Department);
                }
                else
                {
                    await _client.CreateDepartmentAsync(Department);
                }
            }
            catch (Exception e)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show(Properties.Resources.DepartmentSaveFailed, string.Empty, MessageBoxButton.OK, MessageBoxImage.Error);
            }


            window.Close(); ;
        }

        DepartmentServiceClient _client = new DepartmentServiceClient();
    }
}
