using System;
using System.Collections;
using System.IO;

namespace MathSpeakWrite
{
	/// <summary>
	/// Namechecker class used to lookup the names of files in the CIT trainingdir and 
	/// store them in a hashtable. The class can be queried to see if a symbol exists
	/// in that training dr.
	/// </summary>
	public class NameChecker
	{
		public Hashtable filesTable;
		public string dirpath;

		/// <summary>
		/// Requires a path to the data directory containing the files.
		/// </summary>
		/// <param name="path"></param>
		public NameChecker(string path)
		{
			reloadTable(path);
		}
		
		/// <summary>
		/// Reloads the table of files by looking at all files names in the stored dir.
		/// </summary>
		public void reloadTable()
		{
			string [] fns;
			filesTable = new Hashtable();
			fns = Directory.GetFiles(dirpath);

			foreach (string s in fns)
			{
				string name = nameParser(s);
				filesTable.Add(name, name);
			}
		}

		/// <summary>
		/// Reloads the Table of files by looking at all file names in the given directory. 
		/// This stores the given directory name as the path for this NameChecker so if 
		/// reloadTable is called without options, the new path will be used.
		/// </summary>
		/// <param name="path"></param>
		public void reloadTable(string path)
		{
			this.dirpath = path;
			reloadTable();
		}
		
		/// <summary>
		/// Checks to see if the given name is stored in it's table, if so returns true, otherwise false.
		/// </summary>
		/// <param name="name"></param>
		/// <returns></returns>
		public bool containsName(string name)
		{
			if(name == null)
				return false;
			return filesTable.ContainsKey(name);
		}

		/// <summary>
		/// Removes the given name from this NameChecker and deletes the physical file.
		/// </summary>
		/// <param name="name"></param>
		/// <returns></returns>
		public bool deleteFile(string name)
		{
			if(!containsName(name))
				return false;
			else 
			{
				try
				{
					File.Delete(this.dirpath+nameUnParser(name));
				}
				catch
				{
					return false;
				}

				this.filesTable.Remove(name);
				return true;
			}
		}
		
		/// <summary>
		/// Takes a symbol name and converts it to a filename;
		/// </summary>
		/// <param name="parsed"></param>
		/// <returns></returns>
		private string nameUnParser(string parsed)
		{
			if(char.IsLower(parsed[0]))
				parsed = '_' + parsed;
			parsed = parsed + ".0";
			return parsed;
		}
		
		/// <summary>
		/// Takes file names used for CIT files and converts them to the actual character 
		/// "codes", the tokens which should be input into the RDB.
		/// </summary>
		/// <param name="name"></param>
		/// <returns></returns>
		private string nameParser(string name)
		{
			char[] seps = {'_', '.'};
			string[] strs;
			int slashInd = name.LastIndexOf("\\");

			if(slashInd != -1)
				name=name.Substring(slashInd+1);
			
			strs = name.Split(seps);
			if(strs[0].Length ==0 ||  strs[0][0] == '_')
				return strs[1];
			else
				return strs[0];
		}
	}
}
