using System;

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

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

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

		private readonly IObservable<float> _source;

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

			public override void OnNext(float value)
			{
				if (this._hasValue)
				{
					if (value > this._lastValue || float.IsNaN(value))
					{
						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 float _lastValue;
		}
	}
}
