namespace Binge.Generators
{
	using System;
	using System.Collections;
	using System.IO;
	using System.Text;
	using Binge.Bits;

	public abstract class Generator: Binge.Bits.Object
	{
		public Hashtable Namespaces;
		public Encoding FileEncoding;
		public bool ToStdout;

		protected StreamWriter writer;
		protected Indentation tab;
		public string targetDirectory;
		public string supportDirectory;

		private string EndWithDirChar (string dir)
		{
			if (! dir.EndsWith (Path.DirectorySeparatorChar.ToString ()) && dir != String.Empty)
				dir += Path.DirectorySeparatorChar;

			return dir;
		}

		public string TargetDirectory
		{
			get { return targetDirectory; }
			set { targetDirectory = EndWithDirChar (value); }
		}

		public string SupportDirectory
		{
			get { return supportDirectory; }
			set { supportDirectory = EndWithDirChar (value); }
		}

		protected Generator ()
		{
			tab = new Indentation ();
			Namespaces = new Hashtable ();
			TargetDirectory = ".";
			SupportDirectory = ".";
			FileEncoding = new ASCIIEncoding ();
			ToStdout = false;
		}

		protected Generator (string tdir, string sdir): this ()
		{
			targetDirectory = tdir;
			supportDirectory = sdir;
		}

		protected Generator (string tdir, string sdir, Hashtable ns): this (tdir, sdir)
		{
			Namespaces = ns;
		}

		public abstract void Generate ();

		protected void Prnl (string fmt, params object[] arg)
		{
			writer.WriteLine (tab.ToString () + fmt, arg);

			if (ToStdout)
				Outl (tab.ToString () + fmt, arg);
		}

		protected void Prnl (string fmt)
		{
			writer.WriteLine (tab.ToString () + fmt);

			if (ToStdout)
				Outl (tab.ToString () + fmt);
		}

		protected void Prn (string fmt, params object[] arg)
		{
			writer.Write (fmt, arg);

			if (ToStdout)
				Out (fmt, arg);
		}

		protected void Prn (string fmt)
		{
			writer.Write (fmt);

			if (ToStdout)
				Out (fmt);
		}
	}
}
