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

        public ObservableCollection<TimeSheetRecordDto> TimeSheetRecords { 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 ShowTimeSheetStatisticCommand { get; set; }

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

            SelectEmployeeCommand = new RelayCommand(ShowEmployeeSelectWindow);
            ShowTimeSheetStatisticCommand = new RelayCommand(ShowTimeSheetStatistics);

            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 LoadTimeSheetsAsync(BuildFilter()));
        }

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

            var timeSheetRecords = await _timeSheetRecordServiceClient.GetTimeSheetRecordsAsync(filterDto);
            TimeSheetRecords = new ObservableCollection<TimeSheetRecordDto>(timeSheetRecords);
        }

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

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

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

            var monthlyData = new TimeSheetMonthlyData()
            {
                TimeSheetRecords = TimeSheetRecords.ToList(),
                EmployeeName = $"{SelectedEmployee.FirstName} {SelectedEmployee.LastName}",
                MonthName = SelectedMonthComboBoxItem.DisplayName
            };
            var statisticsView = new TimeSheetStatisticsView(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(TimeSheetRecordDto.EmployeeId),
                           Type = ConditionTypeEnum.Equal,
                           Value = SelectedEmployee.Id.ToString()
                      },
                      new ConditionItemDto()
                      {
                           Column = nameof(TimeSheetRecordDto.From),
                           Type = ConditionTypeEnum.GreaterOrEqual,
                           Value = from.ToString("yyyy-MM-dd HH:mm:ss.fff")
                      },
                      new ConditionItemDto()
                      {
                           Column = nameof(TimeSheetRecordDto.To),
                           Type = ConditionTypeEnum.LessOrEqual,
                           Value = to.ToString("yyyy-MM-dd HH:mm:ss.fff")
                      }
                },
                Sorting = new List<SortingItemDto>()
                {
                      new SortingItemDto()
                      {
                           Ascending = false,
                           Column = nameof(TimeSheetRecordDto.From),
                      }
                }
            };

            return filter;
        }

        TimeSheetRecordServiceClient _timeSheetRecordServiceClient = new TimeSheetRecordServiceClient();
    }
}
