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.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using WpfAsyncPack.Command;

namespace Client.ViewModel
{
    public class TimeSheetRecordDetailViewModel : ViewModelBase
    {

        public TimeSheetRecordDto TimeSheetRecord { get; set; }
        public ICommand CancelCommand { get; set; }

        public ICommand SaveTimeSheetRecordCommand { get; set; }
        public ICommand SelectProjectCommand { get; set; }


        public TimeSheetRecordDetailViewModel(TimeSheetRecordDto attendanceRecord)
        {
            _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;

            TimeSheetRecord = attendanceRecord;
            CancelCommand = new RelayCommand<IClosable>(CloseWindow);
            SaveTimeSheetRecordCommand = new AsyncCommand<IClosable>(SaveTimeSheetRecordAsync);
            SelectProjectCommand = new RelayCommand(ShowProjectSelectWindow);

            Messenger.Default.Register<NotificationMessage<ProjectDto>>(this, SelectProject);

        }

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

        private void ShowProjectSelectWindow()
        {
            var hostWindow = new HostWindow(new ProjectsView(true));
            hostWindow.ShowDialog();
        }

        private void SelectProject(NotificationMessage<ProjectDto> message)
        {
            TimeSheetRecord.Project = message.Content;
            TimeSheetRecord.ProjectId = message.Content.Id;
        }

        private async Task SaveTimeSheetRecordAsync(IClosable window)
        {
            var project = await _timeSheetRecordServiceClient.GetTimeSheetRecordByIdAsync(TimeSheetRecord.Id);

            if (project != null)
            {
                await _timeSheetRecordServiceClient.UpdateTimeSheetRecordAsync(TimeSheetRecord);
            }
            else
            {
                await _timeSheetRecordServiceClient.CreateTimeSheetRecordAsync(TimeSheetRecord);
            }

            window.Close();
        }

        TimeSheetRecordServiceClient _timeSheetRecordServiceClient = new TimeSheetRecordServiceClient();
        private bool _isReadOnly = false;
    }
}
