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

        public ObservableCollection<TimeSheetRecordDto> TimeSheets { get; set; }

        public ICommand ShowTimeSheetRecordDetailCommand { get; set; }
        public ICommand GenerateTimeSheetsCommand { get; set; }

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

        public EditTimeSheetsViewModel()
        {
            _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 LoadTimeSheetsAsync(BuildFilter()));
            ShowTimeSheetRecordDetailCommand = new AsyncCommand<TimeSheetRecordDto>(ShowTimeSheetRecordDetailAsync);
            GenerateTimeSheetsCommand = new AsyncCommand(GenerateTimeSheetsRecordsAsync);


            PropertyChanged += OnSelectedMonthChanged;
        }

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

        private async Task LoadTimeSheetsAsync(FilterDto filterDto = null)
        {
            var timesheetRecords = await _client.GetTimeSheetRecordsAsync(filterDto);
            TimeSheets = new ObservableCollection<TimeSheetRecordDto>(timesheetRecords);
        }

        private async Task ShowTimeSheetRecordDetailAsync(TimeSheetRecordDto selectedRecord)
        {
            if (selectedRecord == null) return;

            var detailView = new TimeSheetRecordDetailView(selectedRecord);
            detailView.ShowDialog();
            await LoadTimeSheetsAsync(BuildFilter());
        }

        private async Task GenerateTimeSheetsRecordsAsync(object param = null)
        {
            await _client.GenerateTimeSheetRecordsAsync(UserManager.Instance.CurrentUser.Id, SelectedMonthComboBoxItem.Year, SelectedMonthComboBoxItem.Month);

            await LoadTimeSheetsAsync(BuildFilter());
        }

        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 = UserManager.Instance.CurrentUser.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 _client = new TimeSheetRecordServiceClient();

    }
}
