using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using Telerik.WinControls.UI;
using System.Drawing;
using System.IO;
using System.Reflection;

namespace Telerik.QuickStart.WinControls
{
	class ExamplesLoader
	{
		private bool singleExpand;
		private string examplesTitle;
	    private MainForm mainForm;

		public bool SingleExpand
		{
			get
			{
				return singleExpand;
			}
		}

		public string ExamplesTitle
		{
			get
			{
				return this.examplesTitle;
			}
		}

		public void Load(string filePath, RadTreeView treeView)
		{
            mainForm = ((MainForm)treeView.FindForm());

			if (filePath == null && filePath.Length < 1)
			{
				throw new ApplicationException("ContentFile cannot be empty.");
			}

			XmlDocument xmlDoc = new XmlDocument();
			xmlDoc.Load(filePath);
			XmlNode examples = xmlDoc.SelectSingleNode("/examples");

			XmlNode examplesNode = xmlDoc.SelectSingleNode("//examples");
			if (examplesNode.Attributes["Title"] != null)
			{
				this.examplesTitle = examplesNode.Attributes["Title"].Value;
			}			

			if (examples.Attributes["singleExpand"] != null)
			{
				singleExpand = Convert.ToBoolean(examples.Attributes["singleExpand"].Value);
			}
		
			this.Populate(xmlDoc, treeView);
		}

		private void Populate(XmlDocument xmlDoc, RadTreeView treeView)
		{
			XmlNode rootXmlNode = xmlDoc.SelectSingleNode("/examples");
			RadTreeNode rootNode = new ExamplesTreeNode("telerik WinControls examples", NodeType.Category);

			treeView.BeginUpdate();
			treeView.Nodes.Add(rootNode);
			BuildCategories(rootNode, rootXmlNode, 0);
			treeView.Nodes.Remove(rootNode);
            // here we use the new feature of RadTreeView that when a node is reparented to a different 
            // node collection it clear its refference from the firts one.
            while (rootNode.Nodes.Count > 0)
            {
                treeView.Nodes.Add(rootNode.Nodes[0]);
            }
			treeView.EndUpdate();
		}

        private Image LoadFromFile( string imageFileName )
        {   
            string basePath = Path.GetDirectoryName( Application.ExecutablePath );
            string fullPath = Path.Combine(basePath, imageFileName);
            if (File.Exists(fullPath))
            {
                return Image.FromFile(fullPath);
            }
            return null;
        }
            

		private void BuildCategories(RadTreeNode parentNode, XmlNode parentXmlNode, int depth)
		{
			foreach (XmlNode node in parentXmlNode.ChildNodes)
			{
				if (node.Name == "category")
				{
					ExamplesTreeNode categoryNode = new ExamplesTreeNode(node.Attributes["text"].Value, NodeType.Category);

                    LoadCommonNodeProperties(parentNode, node, categoryNode);

                    //Q1 2009 requirements - Root category nodes are bigger and have more "padding"
                    if (depth == 0)
                    {
                        categoryNode.ItemHeight += 4;
                        categoryNode.Font = new Font("Lucida Sans Unicode", 10.5f);
                    }
                    else
                    {                        
                        categoryNode.Image = mainForm.CategoryNodeImage;
                        categoryNode.StateImage = mainForm.CategoryNodeExpandedImage;
                    }

				    if (node.Attributes["path"] != null)
                    {                        
                        categoryNode.ExampleImage = this.LoadFromFile( node.Attributes["path"].Value );
                    }                

                    if (node.Attributes["DescriptionPath"] != null)
                    {
                        categoryNode.CategoryDescriptionPath = node.Attributes["DescriptionPath"].Value;
                    }

					parentNode.Nodes.Add(categoryNode);
					BuildCategories(categoryNode, node, depth + 1);
				}
				else
				{
					if (node.NodeType != XmlNodeType.Comment)
					{
						ExamplesTreeNode exampleNode = new ExamplesTreeNode(node.Attributes["text"].Value, NodeType.Example);

						exampleNode.Image = mainForm.ExampleNodeImage;

						parentNode.Nodes.Add(exampleNode);
						exampleNode.ExampleTypeName = node.Attributes["name"].Value;

                        if (depth == 0)
                        {
                            exampleNode.ItemHeight += 4;
                            exampleNode.Font = new Font("Lucida Sans Unicode", 10.5f);
                            exampleNode.ForeColor = Color.White;
                        }

                        //add support for rad carousel
                        //pp 22/08/07

                        LoadCommonNodeProperties(parentNode, node, exampleNode);

                        //if (node.Attributes["ImageIndex"] != null)
                        //{
                        //    string imageIndex = node.Attributes["ImageIndex"].Value;
                        //    if (!string.IsNullOrEmpty(imageIndex))
                        //    {
                        //        int res = 0;
                        //        if (int.TryParse(imageIndex, out res))
                        //        {
                        //            exampleElement.ImageIndex = res;
                        //            exampleElement.SelectedImageIndex = res;
                        //        }
                        //    }
                        //}

                        if (node.Attributes[ "ShowInCarousel" ] != null)
                        {
                            string valueShowInCarousel = node.Attributes[ "ShowInCarousel" ].Value.Trim().ToLower();
                            if (valueShowInCarousel == "yes" || 
                                valueShowInCarousel == "1" ||
                                valueShowInCarousel == "true")
                            {
                                exampleNode.ShowInCarousel = true;
                            }
                        }

                        if (node.Attributes[ "ShowInHomeCarousel" ] != null)
                        {
                            string valueShowInHomeCarousel = node.Attributes[ "ShowInHomeCarousel" ].Value.Trim().ToLower();
                            if (valueShowInHomeCarousel == "yes" ||
                                valueShowInHomeCarousel == "1" ||
                                valueShowInHomeCarousel == "true")
                            {
                                exampleNode.ShowInHomeCarousel = true;
                            }
                        }

                        if (node.Attributes["CarouselTitle"] != null)
                        {
                            exampleNode.CarouselTitle = node.Attributes["CarouselTitle"].Value;                            
                        }

                        //end add

						if (node.Attributes["path"] != null)
						{
							exampleNode.Path = node.Attributes["path"].Value;
						}

                        if (node.Attributes["SourceFilesPath"] != null)
                        {
                            exampleNode.SourceFilesPath = node.Attributes["SourceFilesPath"].Value;
                        }
                        else
                        {
                            exampleNode.SourceFilesPath = exampleNode.Path;
                        }

					    if (node.Attributes["formName"] != null)
						{
							exampleNode.FormName = node.Attributes["formName"].Value;
						}
					}
				}
			}
		}

	    private void LoadCommonNodeProperties(RadTreeNode parentNode, XmlNode node, ExamplesTreeNode exampleNode)
	    {
	        if (node.Attributes["ImageName"] != null)
	        {
	            string imageResourceName = node.Attributes["ImageName"].Value;
	            if (!string.IsNullOrEmpty(imageResourceName))
	            {
	                imageResourceName = "Telerik.QuickStart.WinControls.Resources.TreeViewImages." + imageResourceName;
	                Image res = MainForm.ImageFromResource(imageResourceName);
	                if (res != null)
	                {
	                    exampleNode.Image = res;
	                    exampleNode.ItemHeight = res.Height + 2;
	                    exampleNode.ForeColor = Color.White;
	                }
	                //exampleNode.SelectedImageIndex = res;                            
	            }
	        }

            if (node.Attributes["new"] != null)
            {
                exampleNode.ShowFarImage = true;
                exampleNode.FarImage = mainForm.NodeNewImage;
            }

            if (node.Attributes["Theming"] != null)
            {
                string valueTheming = node.Attributes["Theming"].Value.Trim().ToLower();
                if (valueTheming == "yes" ||
                    valueTheming == "1" ||
                    valueTheming == "true")
                {
                    exampleNode.Theming = true;
                }
            }
	    }
	}
}
