using System;

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

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

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

		private readonly IObservable<double> _source;

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

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