﻿using NHibernate.Linq;
using System;
using System.Collections.Generic;
using System.Linq;

namespace DeVi.Models.Repositories
{
	internal class EpisodesRepository : Repository<Episode>, IEpisodesRepository
	{
		public IEnumerable<uint> ExistingIds( IEnumerable<uint> ids )
		{
			var allIds = Session.Query<Episode>().Select( e => e.Id ).ToArray();

			return ids.Intersect( allIds );
		}

		public Dictionary<uint, bool> GetWatchStatus()
		{
			return Session.Query<Episode>().Select( e => new KeyValuePair<uint, bool>( e.Id, e.Watched ) ).ToDictionary( kvp => kvp.Key, kvp => kvp.Value );
		}

		public int UnwatchedEpisodeCount => Session.Query<Episode>().Count( e => !e.Watched );

		public TimeSpan UnwatchedEpisodeTime
		{
			get
			{
				if( !Session.Query<Episode>().Any( e => !e.Watched ) )
				{
					return TimeSpan.Zero;
				}

				long seconds = Session.Query<Episode>().Where( e => !e.Watched ).Sum( e => e.Series.Runtime );
				return TimeSpan.FromMinutes( seconds );
			}
		}

		public int WatchedEpisodeCount => Session.Query<Episode>().Count( e => e.Watched );

		public TimeSpan WatchedEpisodeTime
		{
			get
			{
				if( !Session.Query<Episode>().Any( e => e.Watched ) )
				{
					return TimeSpan.Zero;
				}

				long seconds = Session.Query<Episode>().Where( e => e.Watched ).Sum( e => e.Series.Runtime );
				return TimeSpan.FromMinutes( seconds );
			}
		}
	}
}