using System;
using System.Data;
using System.Collections;
using System.Xml;
using System.IO;
using System.Text.RegularExpressions;
using Orciid.Media.Util;

namespace Localization
{
	public class ResourceConversion
	{
		static XmlElement CreateResHeader(XmlDocument doc, string name, string val)
		{
			XmlElement r = doc.CreateElement("resheader");
			XmlElement v = doc.CreateElement("value");
			v.InnerText = val;
			r.AppendChild(v);
			XmlAttribute a = doc.CreateAttribute("name");
			a.Value = name;
			r.Attributes.Append(a);
			return r;
		}

		[STAThread]
		static void Main() 
		{
			DataTable table = CsvParser.Parse(
				new StreamReader("localization.csv", System.Text.Encoding.Default), true);
			ArrayList docs = new ArrayList();
			ArrayList languages = new ArrayList();

			for (int i = 1; i < table.Columns.Count; i++)
			{
				string lang = table.Columns[i].Caption;
				Console.WriteLine("Detected language {0}", lang);
				languages.Add(lang);
				XmlDocument doc = new XmlDocument();
				XmlElement root = doc.CreateElement("root");					
				root.AppendChild(CreateResHeader(doc, "ResMimeType", "text/microsoft-resx"));
				root.AppendChild(CreateResHeader(doc, "Version", "1.0.0.0"));
				root.AppendChild(CreateResHeader(doc, "Reader", "System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"));
				root.AppendChild(CreateResHeader(doc, "Writer", "System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"));
				doc.AppendChild(root);
				docs.Add(doc);
			}

			foreach (DataRow row in table.Rows)
			{
				for (int i = 1; i < table.Columns.Count; i++)
				{
					XmlDocument doc = (XmlDocument)docs[i - 1];
					XmlNode root = doc.SelectSingleNode("/root");
					XmlElement data = doc.CreateElement("data");
					XmlAttribute name = doc.CreateAttribute("name");
					name.Value = row[0].ToString();
					data.Attributes.Append(name);
					if (row[i] != null && row[i] != DBNull.Value)
					{
						data.InnerText = row[i].ToString();
						root.AppendChild(data);
					}
				}
			}
					
			for (int i = 0; i < languages.Count; i++)
			{
				string lang = languages[i].ToString();
				if (lang == "en-US")
					lang = "";
				else
					lang += ".";

				XmlTextWriter writer = new XmlTextWriter(
					"orciid." + lang + "resx", 
					System.Text.Encoding.Unicode);
				writer.Formatting = Formatting.Indented;
				writer.Indentation = 1;
				writer.IndentChar = '\t';
				((XmlDocument)docs[i]).Save(writer);
				writer.Close();		
			}
		}
	}
}
