using System;
using System.IO;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Resources;
using ResourceDictionary = System.Windows.ResourceDictionary;

namespace SilverlightApplication1
{
	public static class Helper
	{
		private const string DefaultThemeUriFormat = "/Telerik.Windows.Controls.Charting;component/Themes/Generic.xaml";

		public static TResourceType FindResource<TResourceType>(string resourceKey)
		{
			Uri resourcesUri = new Uri(DefaultThemeUriFormat, UriKind.Relative);
			ResourceDictionary dictionary = LoadResourceDictionary(resourcesUri);
			if (dictionary != null && dictionary.Contains(resourceKey))
				return (TResourceType)dictionary[resourceKey];

			return default(TResourceType);
		}

		private static ResourceDictionary LoadResourceDictionary(Uri source)
		{
			StreamResourceInfo sri = null;
			try
			{
				sri = Application.GetResourceStream(source);
				if (sri == null || sri.Stream == null)
				{
					return null;
				}
			}
			catch
			{
				return null;
			}

			using (StreamReader reader = new StreamReader(sri.Stream))
			{
				string resourceString = reader.ReadToEnd();
				return XamlReader.Load(resourceString) as ResourceDictionary;
			}
		}
	}
}
