using System;

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

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

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

		private readonly IObservable<long> _source;

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

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