using System;

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

		protected override DefaultIfEmpty<TSource>._ CreateSink(IObserver<TSource> observer)
		{
			return new DefaultIfEmpty<TSource>._(this._defaultValue, observer);
		}

		protected override void Run(DefaultIfEmpty<TSource>._ sink)
		{
			sink.Run(this._source);
		}

		private readonly IObservable<TSource> _source;

		private readonly TSource _defaultValue;

		internal sealed class _ : IdentitySink<TSource>
		{
			public _(TSource defaultValue, IObserver<TSource> observer)
				: base(observer)
			{
				this._defaultValue = defaultValue;
				this._found = false;
			}

			public override void OnNext(TSource value)
			{
				this._found = true;
				base.ForwardOnNext(value);
			}

			public override void OnCompleted()
			{
				if (!this._found)
				{
					base.ForwardOnNext(this._defaultValue);
				}
				base.ForwardOnCompleted();
			}

			private readonly TSource _defaultValue;

			private bool _found;
		}
	}
}
