using System;
using System.Reactive.Subjects;
using System.Threading;

namespace System.Reactive.Linq.ObservableImpl
{
	internal sealed class AutoConnect<T> : IObservable<T>
	{
		internal AutoConnect(IConnectableObservable<T> source, int minObservers, Action<IDisposable> onConnect)
		{
			this._source = source;
			this._minObservers = minObservers;
			this._onConnect = onConnect;
		}

		public IDisposable Subscribe(IObserver<T> observer)
		{
			IDisposable disposable = this._source.Subscribe(observer);
			if (Volatile.Read(ref this._count) < this._minObservers && Interlocked.Increment(ref this._count) == this._minObservers)
			{
				IDisposable disposable2 = this._source.Connect();
				Action<IDisposable> onConnect = this._onConnect;
				if (onConnect == null)
				{
					return disposable;
				}
				onConnect(disposable2);
			}
			return disposable;
		}

		private readonly IConnectableObservable<T> _source;

		private readonly int _minObservers;

		private readonly Action<IDisposable> _onConnect;

		private int _count;
	}
}
