﻿using DeVi.Resources;
using DeVi.ViewServices;
using GalaSoft.MvvmLight.CommandWpf;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;

namespace DeVi.ViewModels
{
	internal class SeasonEntry : ViewModelBaseEx
	{
		public SeasonEntry( IViewModelContainer viewModelContainer, IDataContainer dataContainer, uint seasonNumber, SeriesEntry series )
			: base( viewModelContainer, dataContainer )
		{
			Series = series;
			SeasonNumber = seasonNumber;
		}

		public void EpisodeWatched()
		{
			RaisePropertyChanged( nameof( UnwatchedEpisodeCount ) );
		}

		private async void ExecuteMarkWatchedCommand( bool watched )
		{
			if( Settings.ConfirmSeasonWatched )
			{
				string message = watched ? Strings.ConfirmMarkWatchedSeasonMessage : Strings.ConfirmMarNotkWatchedSeasonMessage;
				ConfirmationServiceArgs csa = new ConfirmationServiceArgs( Strings.ConfirmAction, message );
				if( !await ViewServices.Execute<IConfirmationService, bool>( csa ) )
				{
					return;
				}

				if( csa.DontAskAgain )
				{
					Settings.ConfirmSeasonWatched = false;
					Settings.Save();
				}
			}

			await ViewModelContainer.BackgroundRunner.Run( stats =>
			{
				foreach( var ep in SeasonEpisodes )
				{
					ep.SetWatched( watched );
				}

				Repositories.Series.Update( Series.Model );
				stats.SetResult( true );
			}, Strings.MarkingEpisodesAsWatched );

			RaisePropertyChanged( nameof( UnwatchedEpisodeCount ) );
			Series.EpisodesWatched();
		}

		public int EpisodeCount => SeasonEpisodes.Count();
		public ICommand MarkWatchedCommand => _MarkWatchedCommand ?? ( _MarkWatchedCommand = new RelayCommand<bool>( ExecuteMarkWatchedCommand ) );
		public uint SeasonNumber { get; }
		public int UnwatchedEpisodeCount => SeasonEpisodes.Count( e => !e.Watched );
		private IEnumerable<EpisodeEntry> SeasonEpisodes => Series.Episodes.Where( e => e.Model.SeasonNumber == SeasonNumber );
		private readonly SeriesEntry Series;
		private RelayCommand<bool> _MarkWatchedCommand;
	}
}