using System;

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

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

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

			private readonly IObservable<TSource> _source;

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

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

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

				private int _count;
			}
		}

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

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

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

			private readonly IObservable<TSource> _source;

			private readonly Func<TSource, bool> _predicate;

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

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

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

				private readonly Func<TSource, bool> _predicate;

				private int _count;
			}
		}
	}
}
