using System;
using System.Runtime.CompilerServices;

namespace RadDockingAndPRISM
{
    internal class WeakReferenceViewFactory : IViewFactory
    {
        public static WeakReferenceViewFactory Instance { get; private set; }

        static WeakReferenceViewFactory()
        {
            Instance = new WeakReferenceViewFactory();

        }
        private ConditionalWeakTable<Type,  WeakReference<object>> viewsStore = new ConditionalWeakTable<Type, WeakReference<object>>();

        private WeakReferenceViewFactory()
        {

        }
        public object GetView(Type value)
        {
            var weakView = viewsStore.GetValue(value, Create);
            object target;
            if (weakView.TryGetTarget(out target))
            {
                return target;
            }
            else {
                viewsStore.Remove(value);
                
                return GetView(value);
            }
        }

        private WeakReference<object> Create(Type key)
        {
            return new WeakReference<object>( Activator.CreateInstance(key));
        }
    }
}