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.ComponentModel;
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 EditAttendanceViewModel : ViewModelBase
    {

        public ObservableCollection<AttendanceRecordDto> AttendanceRecords { get; set; }

        public ICommand ShowAttendanceRecordDetailCommand { get; set; }

        public ICommand DeleteAttendanceRecordCommand { get; set; }
        public ICommand ShowAddNewAttendanceRecordCommand { get; set; }

        public IEnumerable<MonthComboBoxData> MonthComboBoxItems { get; set; }
        public MonthComboBoxData SelectedMonthComboBoxItem { get; set; }

        public EditAttendanceViewModel()
        {
            _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;

            MonthComboBoxItems = MonthComboBoxDataHelper.GetMonthComboBoxData(12);
            SelectedMonthComboBoxItem = MonthComboBoxItems.FirstOrDefault();

            Task.Run(async () => await LoadAttendanceRecordsAsync(BuildFilter()));
            ShowAttendanceRecordDetailCommand = new AsyncCommand<AttendanceRecordDto>(ShowAttendanceRecordDetailAsync);
            DeleteAttendanceRecordCommand = new AsyncCommand<AttendanceRecordDto>(DeleteAttendanceRecordAsync);
            ShowAddNewAttendanceRecordCommand = new AsyncCommand(ShowAddNewAttendanceRecordAsync);


            PropertyChanged += OnSelectedMonthChanged;
        }

        private void OnSelectedMonthChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(SelectedMonthComboBoxItem))
                Task.Run(async () => await LoadAttendanceRecordsAsync(BuildFilter()));
        }

        private async Task LoadAttendanceRecordsAsync(FilterDto filterDto = null)
        {
            var attendanceRecords = await _client.GetAttendanceRecordsAsync(filterDto);
            AttendanceRecords = new ObservableCollection<AttendanceRecordDto>(attendanceRecords);
        }

        private async Task ShowAttendanceRecordDetailAsync(AttendanceRecordDto selectedAttendanceRecord)
        {
            if (selectedAttendanceRecord == null) return;

            var detailView = new AttendanceDetailView(selectedAttendanceRecord);
            detailView.ShowDialog();
            await LoadAttendanceRecordsAsync(BuildFilter());
        }

        private async Task ShowAddNewAttendanceRecordAsync(object param = null)
        {
            var newAttendanceRecord = new AttendanceRecordDto()
            {
                TimeStamp = DateTime.Now,
                EmployeeId = UserManager.Instance.CurrentUser.Id
            };
            var detailView = new AttendanceDetailView(newAttendanceRecord);
            detailView.ShowDialog();
            await LoadAttendanceRecordsAsync(BuildFilter());
        }

        private async Task DeleteAttendanceRecordAsync(AttendanceRecordDto attendanceRecord)
        {
            if (attendanceRecord == null) return;

            var result = Xceed.Wpf.Toolkit.MessageBox.Show(string.Format(Properties.Resources.DeleteAttendanceRecordPrompt, attendanceRecord.Id), string.Empty, MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);

            if (result == MessageBoxResult.Yes)
            {
                await _client.DeleteAttendanceRecordAsync(attendanceRecord.Id);
                await LoadAttendanceRecordsAsync(BuildFilter());
                Xceed.Wpf.Toolkit.MessageBox.Show(Properties.Resources.AttendanceRecordDeleted, string.Empty, MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private FilterDto BuildFilter()
        {

            DateTime from = new DateTime(SelectedMonthComboBoxItem.Year, SelectedMonthComboBoxItem.Month, 1);
            var lastDayOfMonth = from.AddMonths(1).AddDays(-1);
            DateTime to = new DateTime(SelectedMonthComboBoxItem.Year, SelectedMonthComboBoxItem.Month, lastDayOfMonth.Day, 23, 59, 59);

            var filter = new FilterDto()
            {
                Conditions = new List<ConditionItemDto>()
                 {
                      new ConditionItemDto()
                      {
                           Column = nameof(AttendanceRecordDto.EmployeeId),
                           Type = ConditionTypeEnum.Equal,
                           Value = UserManager.Instance.CurrentUser.Id.ToString()
                      },
                      new ConditionItemDto()
                      {
                           Column = nameof(AttendanceRecordDto.TimeStamp),
                           Type = ConditionTypeEnum.GreaterOrEqual,
                           Value = from.ToString("yyyy-MM-dd HH:mm:ss.fff")
                      },
                      new ConditionItemDto()
                      {
                           Column = nameof(AttendanceRecordDto.TimeStamp),
                           Type = ConditionTypeEnum.LessOrEqual,
                           Value = to.ToString("yyyy-MM-dd HH:mm:ss.fff")
                      }
                 },
                 Sorting = new List<SortingItemDto>()
                 {
                      new SortingItemDto()
                      {
                           Ascending = false,
                           Column = nameof(AttendanceRecordDto.TimeStamp),
                      }
                 }
            };

            return filter;
        }

        AttendanceRecordServiceClient _client = new AttendanceRecordServiceClient();

    }
}
