using System;

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

		public IObservable<TSource> Dematerialize()
		{
			return this._source.AsObservable<TSource>();
		}

		protected override Materialize<TSource>._ CreateSink(IObserver<Notification<TSource>> observer)
		{
			return new Materialize<TSource>._(observer);
		}

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

		private readonly IObservable<TSource> _source;

		internal sealed class _ : Sink<TSource, Notification<TSource>>
		{
			public _(IObserver<Notification<TSource>> observer)
				: base(observer)
			{
			}

			public override void OnNext(TSource value)
			{
				base.ForwardOnNext(Notification.CreateOnNext<TSource>(value));
			}

			public override void OnError(Exception error)
			{
				base.ForwardOnNext(Notification.CreateOnError<TSource>(error));
				base.ForwardOnCompleted();
			}

			public override void OnCompleted()
			{
				base.ForwardOnNext(Notification.CreateOnCompleted<TSource>());
				base.ForwardOnCompleted();
			}
		}
	}
}
