using System;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.Windows.Forms;

namespace Support_pedagogique_numerique
{
	/// <summary>
	/// Classe de génération des .docBook et .dc à partir de l'arborescence des répertoires
	/// </summary>
	class gen
	{
		static public void DirContent(XmlNode targetNode, string targetDirectory)
		{
			int l = targetDirectory.Length + 1;
			try 
			{
				string [] fileEntries = System.IO.Directory.GetFiles(targetDirectory);
				foreach(string fileName in fileEntries)
				{
					XmlElement FileNode = targetNode.OwnerDocument.CreateElement("File");
					FileNode.SetAttribute("name", fileName.Substring(l));
					//MessageBox.Show("nom trop long : "+ fileName);
					try 
					{
						System.IO.FileInfo finf = new System.IO.FileInfo(fileName);
						if( finf.CreationTime < finf.LastWriteTime )
						{
							FileNode.SetAttribute("date.created", finf.CreationTime.ToString("s"));
						}
						else
						{
							FileNode.SetAttribute("date.created", finf.LastWriteTime.ToString("s"));
						}
						FileNode.SetAttribute("date.modified", finf.LastWriteTime.ToString("s"));
						targetNode.AppendChild(FileNode);
					}
					catch (Exception exc) 
					{
						MessageBox.Show("nom trop long : "+ fileName);
					}
				}

				string [] subdirectoryEntries = System.IO.Directory.GetDirectories(targetDirectory);
				foreach(string subdirectory in subdirectoryEntries)
				{
					XmlElement FolderNode = targetNode.OwnerDocument.CreateElement("Folder");
					FolderNode.SetAttribute("name", subdirectory.Substring(l));
					DirContent(FolderNode, subdirectory);
					targetNode.AppendChild(FolderNode);
				}
			} 
			catch(Exception e) 
			{
				MessageBox.Show("Exception lors de la génération des fichiers DocBook : "+ e.ToString());
				Application.Exit();
			}
		}
		/// <summary>
		/// Point d'entrée principal de l'application.
		/// </summary>
		/// 
		public static void genererDc()
		{
			try
			{
				XmlDocument xDoc;

				// Mise à jour des notices DC

				xDoc = new XmlDocument();
				XmlElement root = xDoc.CreateElement("Folder");
				root.SetAttribute("name", "documents");
				root.SetAttribute("path", @"..\documents");
				DirContent(root, @"..\documents");
				xDoc.AppendChild(root);
				XPathNavigator nav = root.CreateNavigator();
				XslTransform xslt = new XslTransform();
				xslt.Load(Config.dcgen_xsl);
				StringWriter writer = new StringWriter();
				xslt.Transform(nav, null, writer, new XmlUrlResolver());
				xDoc.LoadXml(writer.ToString());
				foreach(XmlElement xFile in xDoc.SelectNodes("/Changes/File[@action='write']"))
				{
					XmlTextWriter xw = new XmlTextWriter(xFile.GetAttribute("path"), null);
					xw.Formatting = Formatting.Indented;
					xFile.FirstChild.WriteTo(xw);
					xw.Flush();
					xw.Close();
					StreamReader sr = new StreamReader(xFile.GetAttribute("path"));
					String s = sr.ReadToEnd();
					sr.Close();
					StreamWriter sw = new StreamWriter(xFile.GetAttribute("path"));
					sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
					sw.Write(s);
					sw.Flush();
					sw.Close();
				}
				foreach(XmlElement xFile in xDoc.SelectNodes("/Changes/File[@action='delete']"))
				{
					File.Delete(xFile.GetAttribute("path"));
				}
			}
			catch(Exception e)
			{
				MessageBox.Show ("Exception lors de la génération des fichiers DC : "+ e.ToString());
				Application.Exit();
			}
		}

		public static void genererDocBook()
		{
			try
			{
				// Mise à jour des documents DocBook

				XmlDocument xDoc = new XmlDocument();
				XmlElement root = xDoc.CreateElement("Folder");
				root.SetAttribute("name", "documents");
				root.SetAttribute("path", @"..\documents");
				DirContent(root, @"..\documents");
				xDoc.AppendChild(root);
				XPathNavigator nav = root.CreateNavigator();
				XslTransform xslt = new XslTransform();
				xslt.Load(Config.docbookgen_xsl);
				StringWriter writer = new StringWriter();
				xslt.Transform(nav, null, writer, new XmlUrlResolver());
				xDoc.LoadXml(writer.ToString());
				foreach(XmlElement xFile in xDoc.SelectNodes("/Changes/File[@action='write']"))
				{
					XmlTextWriter xw = new XmlTextWriter(xFile.GetAttribute("path"), null);
					xw.Formatting = Formatting.Indented;
					xFile.FirstChild.WriteTo(xw);
					xw.Flush();
					xw.Close();
					StreamReader sr = new StreamReader(xFile.GetAttribute("path"));
					String s = sr.ReadToEnd();
					sr.Close();
					StreamWriter sw = new StreamWriter(xFile.GetAttribute("path"));
					sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
					sw.Write(s);
					sw.Flush();
					sw.Close();
				}
				foreach(XmlElement xFile in xDoc.SelectNodes("/Changes/File[@action='delete']"))
				{
					File.Delete(xFile.GetAttribute("path"));
				}
			}
			catch(Exception e)
			{
				MessageBox.Show ("Exception lors de la génération des fichiers DocBook : "+ e.ToString());
				Application.Exit();
			}
		}

		public static void genererIndexDocBook()
		{
			try
			{
				// Création du document DocBook de synthèse
				XmlDocument xDoc = new XmlDocument();
				xDoc.Load(@"..\documents\documents.docbook");
				XPathNavigator nav = xDoc.CreateNavigator();
				XslTransform xslt = new XslTransform();
				xslt.Load("docbookindex.xsl");
				StringWriter writer = new StringWriter();
				xslt.Transform(nav, null, writer, new XmlUrlResolver());
				xDoc.LoadXml(writer.ToString());
				XmlTextWriter xwriter = new XmlTextWriter(Config.index_docbook, null);
				xwriter.Formatting = Formatting.Indented;
				xDoc.WriteTo(xwriter);
				xwriter.Flush();
				xwriter.Close();
				StreamReader sr0 = new StreamReader(Config.index_docbook);
				String s0 = sr0.ReadToEnd();
				sr0.Close();
				StreamWriter sw0 = new StreamWriter(Config.index_docbook);
				sw0.Write(s0.Replace("utf-16", "UTF-8"));
				sw0.Flush();
				sw0.Close();

				// Création du fichier index.htm

				nav = xDoc.CreateNavigator();
				xslt = new XslTransform();
				xslt.Load("htmlindex.xsl");
				StreamWriter sw1 = new StreamWriter(@"..\index.htm");
				xslt.Transform(nav, null, sw1, new XmlUrlResolver());
				sw1.Flush();
				sw1.Close();
			}
			catch(Exception e)
			{
				MessageBox.Show ("Exception lors de la génération du fichier index DocBook : "+ e.ToString());
				Application.Exit();
			}
		}
	}
}
