using System;

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

		public Synchronize(IObservable<TSource> source)
		{
			this._source = source;
		}

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

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

		private readonly IObservable<TSource> _source;

		private readonly object _gate;

		internal sealed class _ : IdentitySink<TSource>
		{
			public _(object gate, IObserver<TSource> observer)
				: base(observer)
			{
				this._gate = gate ?? new object();
			}

			public override void OnNext(TSource value)
			{
				object gate = this._gate;
				lock (gate)
				{
					base.ForwardOnNext(value);
				}
			}

			public override void OnError(Exception error)
			{
				object gate = this._gate;
				lock (gate)
				{
					base.ForwardOnError(error);
				}
			}

			public override void OnCompleted()
			{
				object gate = this._gate;
				lock (gate)
				{
					base.ForwardOnCompleted();
				}
			}

			private readonly object _gate;
		}
	}
}
