using Client.DataStructures;
using Client.Helpers;
using Client.ISServiceRef;
using Client.View;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
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 EmployeesAttendanceViewModel : ViewModelBase
    {

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

        public IEnumerable<MonthComboBoxData> MonthComboBoxItems { get; set; }
        public MonthComboBoxData SelectedMonthComboBoxItem { get; set; }
        public EmployeeDto SelectedEmployee { get; set; }
            
        public ICommand SelectEmployeeCommand { get; set; }
        public ICommand ShowAttendanceStatisticsCommand { get; set; }

        public EmployeesAttendanceViewModel()
        {
            _attendanceRecordServiceClient.ClientCredentials.UserName.UserName = UserManager.Instance.CurrentUser.Login;
            _attendanceRecordServiceClient.ClientCredentials.UserName.Password = UserManager.Instance.CurrentUser.Password;
            _attendanceRecordServiceClient.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;

            SelectEmployeeCommand = new RelayCommand(ShowEmployeeSelectWindow);
            ShowAttendanceStatisticsCommand = new RelayCommand(ShowAttendanceStatistics);

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

            PropertyChanged += OnSelectedEmployeeMonthChanged;

            Messenger.Default.Register<NotificationMessage<EmployeeDto>>(this, SelectEmployee);
        }

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

        private async Task LoadAttendanceRecordsAsync(FilterDto filterDto = null)
        {
            if (SelectedEmployee == null) return;

            var attendanceRecords = await _attendanceRecordServiceClient.GetAttendanceRecordsAsync(filterDto);
            AttendanceRecords = new ObservableCollection<AttendanceRecordDto>(attendanceRecords);
        }

        private void ShowEmployeeSelectWindow()
        {
            var hostWindow = new HostWindow(new EmployeesView(true));
            hostWindow.ShowDialog();
        }

        private void SelectEmployee(NotificationMessage<EmployeeDto> message)
        {
            SelectedEmployee = message.Content;
        }

        private void ShowAttendanceStatistics()
        {
            if (SelectedEmployee == null) return;

            var monthlyData = new MonthlyAttendanceData()
            {
                AttendanceRecords = AttendanceRecords.ToList(),
                EmployeeName = $"{SelectedEmployee.FirstName} {SelectedEmployee.LastName}",
                MonthName = SelectedMonthComboBoxItem.DisplayName
            };
            var statisticsView = new AttendanceStatisticsView(monthlyData);

            statisticsView.ShowDialog();
        }

        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 = SelectedEmployee.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 _attendanceRecordServiceClient = new AttendanceRecordServiceClient();
    }
}
