using System;
using System.ComponentModel.Composition;
using Microsoft.Practices.Prism.Regions;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace MarkOn.Infrastructure
{
	[Export(typeof(AutoPopulateExportedViewsBehavior))]
	[PartCreationPolicy(CreationPolicy.NonShared)]
	public class AutoPopulateExportedViewsBehavior : RegionBehavior, IPartImportsSatisfiedNotification
	{
		protected override void OnAttach()
		{
			AddRegisteredViews();
		}

		public void OnImportsSatisfied()
		{
			AddRegisteredViews();
		}

		private void AddRegisteredViews()
		{
			if (this.Region != null)
			{
				foreach (var item in RegisteredViews)
				{
					if (item.Metadata.RegionName == this.Region.Name)
					{
						var view = item.Value;

						if (!this.Region.Views.Contains(view))
						{
							this.Region.Add(view);
						}
					}
				}
			}
		}
	
		[ImportMany(AllowRecomposition = true)]
		public Lazy<object, IViewRegionRegistration>[] RegisteredViews { get; set; }
	}
}