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

        public ICommand CancelCommand { get; set; }

        public ICommand SavePositionCommand { get; set; }
        
        public EmployeePositionDto Position { get; set; }

        public PositionDetailViewModel(EmployeePositionDto position)
        {
            _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;

            Position = position;
            SavePositionCommand = new AsyncCommand<IClosable>(SavePositionAsync);
            CancelCommand = new RelayCommand<IClosable>(CloseWindow);
        }

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


        private async Task SavePositionAsync(IClosable window)
        {

            var department = await _client.GetEmployeePositionByIdAsync(Position.Id);

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


            window.Close(); ;
        }

        EmployeePositionServiceClient _client = new EmployeePositionServiceClient();
    }
}
