using System;

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

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

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

		private readonly IObservable<int> _source;

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

			public override void OnNext(int 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 int _lastValue;
		}
	}
}
