using System;

namespace System.Reactive.Linq.ObservableImpl
{
	internal sealed class MinDecimal : Producer<decimal, MinDecimal._>
	{
		public MinDecimal(IObservable<decimal> source)
		{
			this._source = source;
		}

		protected override MinDecimal._ CreateSink(IObserver<decimal> observer)
		{
			return new MinDecimal._(observer);
		}

		protected override void Run(MinDecimal._ sink)
		{
			sink.Run(this._source);
		}

		private readonly IObservable<decimal> _source;

		internal sealed class _ : IdentitySink<decimal>
		{
			public _(IObserver<decimal> observer)
				: base(observer)
			{
			}

			public override void OnNext(decimal value)
			{
				if (this._hasValue)
				{
					if (value < this._lastValue)
					{
						this._lastValue = value;
						return;
					}
				}
				else
				{
					this._lastValue = value;
					this._hasValue = true;
				}
			}

			public override void OnCompleted()
			{
				if (!this._hasValue)
				{
					base.ForwardOnError(new InvalidOperationException(Strings_Linq.NO_ELEMENTS));
					return;
				}
				base.ForwardOnNext(this._lastValue);
				base.ForwardOnCompleted();
			}

			private bool _hasValue;

			private decimal _lastValue;
		}
	}
}
