using System;

namespace System.Reactive.Linq.ObservableImpl
{
	internal static class LongCount<TSource>
	{
		internal sealed class All : Producer<long, LongCount<TSource>.All._>
		{
			public All(IObservable<TSource> source)
			{
				this._source = source;
			}

			protected override LongCount<TSource>.All._ CreateSink(IObserver<long> observer)
			{
				return new LongCount<TSource>.All._(observer);
			}

			protected override void Run(LongCount<TSource>.All._ sink)
			{
				sink.Run(this._source);
			}

			private readonly IObservable<TSource> _source;

			internal sealed class _ : Sink<TSource, long>
			{
				public _(IObserver<long> observer)
					: base(observer)
				{
				}

				public override void OnNext(TSource value)
				{
					checked
					{
						try
						{
							this._count += 1L;
						}
						catch (Exception ex)
						{
							base.ForwardOnError(ex);
						}
					}
				}

				public override void OnCompleted()
				{
					base.ForwardOnNext(this._count);
					base.ForwardOnCompleted();
				}

				private long _count;
			}
		}

		internal sealed class Predicate : Producer<long, LongCount<TSource>.Predicate._>
		{
			public Predicate(IObservable<TSource> source, Func<TSource, bool> predicate)
			{
				this._source = source;
				this._predicate = predicate;
			}

			protected override LongCount<TSource>.Predicate._ CreateSink(IObserver<long> observer)
			{
				return new LongCount<TSource>.Predicate._(this._predicate, observer);
			}

			protected override void Run(LongCount<TSource>.Predicate._ sink)
			{
				sink.Run(this._source);
			}

			private readonly IObservable<TSource> _source;

			private readonly Func<TSource, bool> _predicate;

			internal sealed class _ : Sink<TSource, long>
			{
				public _(Func<TSource, bool> predicate, IObserver<long> observer)
					: base(observer)
				{
					this._predicate = predicate;
				}

				public override void OnNext(TSource value)
				{
					checked
					{
						try
						{
							if (this._predicate(value))
							{
								this._count += 1L;
							}
						}
						catch (Exception ex)
						{
							base.ForwardOnError(ex);
						}
					}
				}

				public override void OnCompleted()
				{
					base.ForwardOnNext(this._count);
					base.ForwardOnCompleted();
				}

				private readonly Func<TSource, bool> _predicate;

				private long _count;
			}
		}
	}
}
