using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Globalization;

namespace Support_pedagogique_numerique
{
	/// <summary>
	/// Description résumée de Form_arbo.
	/// </summary>
	public class Form_arbo : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Panel panel1;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.GroupBox groupBox3;
		private System.Windows.Forms.ComboBox cb_position_noeud;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.TextBox tb_url_noeud;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.TextBox tb_nom_noeud;
		private System.Windows.Forms.GroupBox groupBox2;
		private System.Windows.Forms.TreeView tv;
		private System.Windows.Forms.Button btn_suivant;
		private System.Windows.Forms.Button btn_precedent;
		
		XmlDocument xmlDoc;

		private System.ComponentModel.Container components = null;

		public Form_arbo()
		{
			//
			// Requis pour la prise en charge du Concepteur Windows Forms
			//
			InitializeComponent();

			// Chargement du fichier XML
			xmlDoc = new  XmlDocument();
			try 
			{
				xmlDoc.Load(Config.index_docbook);
			}
			catch(Exception ex) 
			{
				MessageBox.Show("Impossible de trouver le fichier"+ Config.index_docbook +". Celui-ci doit se trouver dans le même répertoire que cet outil.");
				Application.Exit();
			}
			// Création du TreeView
			xmlToTreeview(xmlDoc, tv);
		}

		/// <summary>
		/// Nettoyage des ressources utilisées.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		// Construction d'un Treeview à partir d'un document docbook type
		public void xmlToTreeview(XmlDocument xd, TreeView t) 
		{
			// Vidage du TreeView
			t.Nodes.Clear();
			// On construit un élément racine
			TreeNode index=new TreeNode("index");
			MyNodeTag mnt = new MyNodeTag();
			mnt.type="racine";
			index.Tag=mnt;
			t.Nodes.Add(index);
			XmlNode section_racine=xmlDoc.SelectSingleNode("article/section/section");
			// Construction du TreeView grâce à la fonction récursive construireBranche
			construireBranche(index, section_racine);
			index.Expand();
		}
		// Fonction de base de construction de l'arbre
		public void construireBranche (TreeNode tn_racine, XmlNode xn) 
		{
			// Construction des noeuds documents (qui n'ont pas de descendants)
			XmlNodeList noeuds_documents=xn.SelectNodes("itemizedlist/listitem/para/ulink");
			foreach (XmlNode document in noeuds_documents) 
			{
				TreeNode tn = new TreeNode(document.InnerText);
				// Ajout des propriétés du noeud
				MyNodeTag mnt = new MyNodeTag();
				mnt.type="document";
				mnt.url=document.Attributes.Item(0).InnerText;
				tn.Tag=mnt;
				tn_racine.Nodes.Add(tn);
			}
			// Construction des branches (sections) enfants de ce noeud
			XmlNodeList noeuds_sections=xn.SelectNodes("section");
			foreach (XmlNode section in noeuds_sections)
			{
				XmlNode titre=section.SelectSingleNode("title");
				TreeNode tn = new TreeNode(titre.InnerText);
				// Ajout des propriétés du noeud
				MyNodeTag mnt = new MyNodeTag();
				mnt.type="section";
				tn.Tag=mnt;
				tn_racine.Nodes.Add(tn);
				// récursivement, on construit la branche de ce noeud
				construireBranche(tn, section);
			}
		}

		// Reconstruction du fichier XML à partir du TreeView
		public void treeviewToXml(TreeView t, XmlDocument xd) 
		{
			// Chargement du fichier XML
			xmlDoc = new  XmlDocument();
			try 
			{
				xmlDoc.Load(Config.index_docbook);
			}
			catch(Exception ex) 
			{
				MessageBox.Show("Impossible de trouver le fichier index.docbook. Celui-ci doit se trouver dans le même répertoire que cet outil.");
				this.Close();
				Application.Exit();
			}
			XmlNode section_racine=xmlDoc.SelectSingleNode("article/section/section");
			// Vidage du contenu de la section racine
			section_racine.RemoveAll();
			// reconstruction du fichier
			construireSection(tv.TopNode, section_racine);
			XmlTextWriter writer = new XmlTextWriter(Config.index_docbook, null);
			writer.Formatting = Formatting.Indented;
			xmlDoc.WriteContentTo(writer);
			writer.Close();
		}

		// Fonction de base de construction d'une section dans le document XML
		public void construireSection (TreeNode tn_racine, XmlNode xn_section) 
		{
			XmlElement liste_docs = xmlDoc.CreateElement("itemizedlist");	
			// les documents
			foreach (TreeNode tn in tn_racine.Nodes) 
			{
				if (((MyNodeTag)tn.Tag).type=="document") 
				{
					XmlElement listitem = xmlDoc.CreateElement("listitem");
					XmlElement para = xmlDoc.CreateElement("para");
					XmlElement ulink = xmlDoc.CreateElement("ulink");
					ulink.SetAttribute("url", ((MyNodeTag)tn.Tag).url);
					ulink.InnerText=tn.Text;
					para.AppendChild(ulink);
					listitem.AppendChild(para);
					liste_docs.AppendChild(listitem);
				}		
			}
			xn_section.AppendChild(liste_docs);
			// les sections
			foreach (TreeNode tn in tn_racine.Nodes) 
			{
				if (((MyNodeTag)tn.Tag).type=="section") 
				{
					XmlElement section = xmlDoc.CreateElement("section");
					XmlElement titre = xmlDoc.CreateElement("title");
					titre.InnerText=tn.Text;
					section.AppendChild(titre);
					xn_section.AppendChild(section);
					construireSection(tn, section);
				}
			}
		}

		// Un noeud de l'arbre a été sélectionné, 
		// on affiche les valeurs correspondantes à droite
		private void tv_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
		{
			/*int total=tv.SelectedNode.Index+1;
			MessageBox.Show(total.ToString());*/
			// Si on sélectionne la racine, on n'affiche rien à droite
			if (((MyNodeTag)tv.SelectedNode.Tag).type=="racine") 
			{
				tb_nom_noeud.Clear();
				tb_url_noeud.Clear();
				cb_position_noeud.Items.Clear();
				cb_position_noeud.Text="";
			}
			else 
			{
				tb_nom_noeud.Text=tv.SelectedNode.Text;
				// Initialisation de la ListBox de position
				TreeNode tn_parent=tv.SelectedNode.Parent;
				
				cb_position_noeud.Items.Clear();
				for (int i=1; i<=tn_parent.GetNodeCount(false); i++)
					cb_position_noeud.Items.Add(i);
				cb_position_noeud.SelectedItem=tv.SelectedNode.Index+1;
				tb_url_noeud.Clear();
				// cas d'un document : on ajoute l'URL
				if (((MyNodeTag)tv.SelectedNode.Tag).type=="document")
					tb_url_noeud.Text=((MyNodeTag)tv.SelectedNode.Tag).url;
			}
		}

		// Changement de valeur dans la liste déroulante de position
		// d'un TreeNode : on le déplace à la bonne position
		private void cb_position_noeud_SelectionChangeCommitted(object sender, System.EventArgs e)
		{
			// Si on sélectionne la racine, on ne fait rien
			if (((MyNodeTag)tv.SelectedNode.Tag).type!="racine" && cb_position_noeud.SelectedItem.ToString()!="") 
			{
				Cursor.Current = Cursors.WaitCursor;
				TreeNode tn_parent = tv.SelectedNode.Parent;
				// Position où déplacer le noeud
				int nv_pos=int.Parse(cb_position_noeud.SelectedItem.ToString())-1;
				// Clonage du TreeNode
				TreeNode tn_copie = (TreeNode)tv.SelectedNode.Clone();
				// On retire le TreeNode d'origine
				tv.SelectedNode.Remove();
				// On réinsère à l'endroit spécifié dans la liste déroulante de position
				tn_parent.Nodes.Insert(nv_pos, tn_copie);
				tv.Refresh();
				tv.SelectedNode=tn_copie;
				Cursor.Current = Cursors.Default;
			}
		}

		#region Code généré par le Concepteur Windows Form
		/// <summary>
		/// Méthode requise pour la prise en charge du concepteur - ne modifiez pas
		/// le contenu de cette méthode avec l'éditeur de code.
		/// </summary>
		private void InitializeComponent()
		{
			this.panel1 = new System.Windows.Forms.Panel();
			this.label1 = new System.Windows.Forms.Label();
			this.groupBox3 = new System.Windows.Forms.GroupBox();
			this.cb_position_noeud = new System.Windows.Forms.ComboBox();
			this.label3 = new System.Windows.Forms.Label();
			this.label2 = new System.Windows.Forms.Label();
			this.tb_url_noeud = new System.Windows.Forms.TextBox();
			this.label4 = new System.Windows.Forms.Label();
			this.tb_nom_noeud = new System.Windows.Forms.TextBox();
			this.groupBox2 = new System.Windows.Forms.GroupBox();
			this.tv = new System.Windows.Forms.TreeView();
			this.btn_suivant = new System.Windows.Forms.Button();
			this.btn_precedent = new System.Windows.Forms.Button();
			this.panel1.SuspendLayout();
			this.groupBox3.SuspendLayout();
			this.groupBox2.SuspendLayout();
			this.SuspendLayout();
			// 
			// panel1
			// 
			this.panel1.BackColor = System.Drawing.Color.White;
			this.panel1.Controls.Add(this.label1);
			this.panel1.Location = new System.Drawing.Point(0, 0);
			this.panel1.Name = "panel1";
			this.panel1.Size = new System.Drawing.Size(744, 48);
			this.panel1.TabIndex = 2;
			// 
			// label1
			// 
			this.label1.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.label1.Location = new System.Drawing.Point(8, 16);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(312, 24);
			this.label1.TabIndex = 0;
			this.label1.Text = "Document arrangement";
			// 
			// groupBox3
			// 
			this.groupBox3.Controls.Add(this.cb_position_noeud);
			this.groupBox3.Controls.Add(this.label3);
			this.groupBox3.Controls.Add(this.label2);
			this.groupBox3.Controls.Add(this.tb_url_noeud);
			this.groupBox3.Controls.Add(this.label4);
			this.groupBox3.Controls.Add(this.tb_nom_noeud);
			this.groupBox3.Location = new System.Drawing.Point(359, 64);
			this.groupBox3.Name = "groupBox3";
			this.groupBox3.Size = new System.Drawing.Size(368, 368);
			this.groupBox3.TabIndex = 5;
			this.groupBox3.TabStop = false;
			this.groupBox3.Text = "Properties";
			// 
			// cb_position_noeud
			// 
			this.cb_position_noeud.Location = new System.Drawing.Point(312, 160);
			this.cb_position_noeud.Name = "cb_position_noeud";
			this.cb_position_noeud.Size = new System.Drawing.Size(40, 21);
			this.cb_position_noeud.TabIndex = 5;
			this.cb_position_noeud.SelectionChangeCommitted += new System.EventHandler(this.cb_position_noeud_SelectionChangeCommitted);
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(232, 160);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(72, 24);
			this.label3.TabIndex = 4;
			this.label3.Text = "Position";
			this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(8, 104);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(72, 16);
			this.label2.TabIndex = 3;
			this.label2.Text = "URL";
			this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
			// 
			// tb_url_noeud
			// 
			this.tb_url_noeud.Location = new System.Drawing.Point(88, 104);
			this.tb_url_noeud.Name = "tb_url_noeud";
			this.tb_url_noeud.ReadOnly = true;
			this.tb_url_noeud.Size = new System.Drawing.Size(264, 20);
			this.tb_url_noeud.TabIndex = 2;
			this.tb_url_noeud.Text = "";
			// 
			// label4
			// 
			this.label4.Location = new System.Drawing.Point(8, 64);
			this.label4.Name = "label4";
			this.label4.Size = new System.Drawing.Size(72, 16);
			this.label4.TabIndex = 1;
			this.label4.Text = "Name";
			this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
			// 
			// tb_nom_noeud
			// 
			this.tb_nom_noeud.Location = new System.Drawing.Point(88, 64);
			this.tb_nom_noeud.Name = "tb_nom_noeud";
			this.tb_nom_noeud.ReadOnly = true;
			this.tb_nom_noeud.Size = new System.Drawing.Size(264, 20);
			this.tb_nom_noeud.TabIndex = 0;
			this.tb_nom_noeud.Text = "";
			// 
			// groupBox2
			// 
			this.groupBox2.Controls.Add(this.tv);
			this.groupBox2.Location = new System.Drawing.Point(15, 64);
			this.groupBox2.Name = "groupBox2";
			this.groupBox2.Size = new System.Drawing.Size(336, 368);
			this.groupBox2.TabIndex = 4;
			this.groupBox2.TabStop = false;
			this.groupBox2.Text = "Document tree structure";
			// 
			// tv
			// 
			this.tv.ImageIndex = -1;
			this.tv.Location = new System.Drawing.Point(16, 24);
			this.tv.Name = "tv";
			this.tv.SelectedImageIndex = -1;
			this.tv.Size = new System.Drawing.Size(304, 336);
			this.tv.TabIndex = 0;
			this.tv.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tv_AfterSelect);
			// 
			// btn_suivant
			// 
			this.btn_suivant.Location = new System.Drawing.Point(616, 440);
			this.btn_suivant.Name = "btn_suivant";
			this.btn_suivant.Size = new System.Drawing.Size(80, 24);
			this.btn_suivant.TabIndex = 7;
			this.btn_suivant.Text = "Next >";
			this.btn_suivant.Click += new System.EventHandler(this.btn_suivant_Click);
			// 
			// btn_precedent
			// 
			this.btn_precedent.Location = new System.Drawing.Point(528, 440);
			this.btn_precedent.Name = "btn_precedent";
			this.btn_precedent.Size = new System.Drawing.Size(80, 24);
			this.btn_precedent.TabIndex = 9;
			this.btn_precedent.Text = "< Back";
			this.btn_precedent.Click += new System.EventHandler(this.btn_precedent_Click);
			// 
			// Form_arbo
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(742, 478);
			this.Controls.Add(this.btn_precedent);
			this.Controls.Add(this.btn_suivant);
			this.Controls.Add(this.groupBox3);
			this.Controls.Add(this.groupBox2);
			this.Controls.Add(this.panel1);
			this.Name = "Form_arbo";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "Documentation index generation tool";
			this.Closed += new System.EventHandler(this.Form_arbo_Closed);
			this.panel1.ResumeLayout(false);
			this.groupBox3.ResumeLayout(false);
			this.groupBox2.ResumeLayout(false);
			this.ResumeLayout(false);

		}
		#endregion

		private void Form_arbo_Closed(object sender, System.EventArgs e)
		{
			Form_intro.frm_params.Show();
			Form_intro.frm_params.Activate();
		}

		private void btn_precedent_Click(object sender, System.EventArgs e)
		{
			this.Close();
		}

		private void btn_suivant_Click(object sender, System.EventArgs e)
		{
			treeviewToXml(tv, xmlDoc);
			Form_intro.frm_index_htm = new Form_index_htm();
			this.Hide();
			Form_intro.frm_index_htm.Show();
			Form_intro.frm_index_htm.Activate();
			Form_intro.frm_index_htm.demarrerGeneration();
		}
	}

	// classe contenant les propriétés d'un noeud de l'arbre
	public class MyNodeTag 
	{
		public string type; // section ou document
		public string url; // seulement pour les documents
	}
}
