// Goldie: GOLD Engine for D
// Tools: Generate Documentation
// Written in the D programming language.

module tools.gendocs.cmd;

import std.path;
import std.stdio;

import semitwist.cmdlineparser;
import semitwist.util.all;

import goldie.all;
import tools.util;

class CmdArgs
{
	mixin(getter!(bool, "shouldExit"));

	public this(string[] args)
	{
		init();
		shouldExit = !parse(args);
	}
	
	// Direct command-line args
	public bool help;
	public bool detailhelp;
	public bool saveAST=false;
	public bool quietMode=false;
	public bool trimLinks=false;
	
	public string astDir  = "";
	public string outFile = "index.html";
	public string outDir  = ".";
	public string srcFile = "";

	// Generated
	public string srcDir = "";

	// Private ------
	private CmdLineParser cmd;
	
	private void init()
	{
		cmd = new CmdLineParser();
		mixin(defineArg!(cmd, "help",   help,       ArgFlag.Optional, "Displays a help summary and exits" ));
		mixin(defineArg!(cmd, "detail", detailhelp, ArgFlag.Optional, "Displays a detailed help message and exits" ));

		mixin(defineArg!(cmd, "",   srcFile, ArgFlag.Required, "Main template file" ));
		mixin(defineArg!(cmd, "od", outDir,  ArgFlag.Optional, "Output directory" ));
		mixin(defineArg!(cmd, "of", outFile, ArgFlag.Optional, "Filename of output pages" ));
		
		mixin(defineArg!(cmd, "trimlink", trimLinks, ArgFlag.Optional, "Trim filename from internal links" ));

		mixin(defineArg!(cmd, "q",    quietMode, ArgFlag.Optional, "Quiet mode" ));
		mixin(defineArg!(cmd, "ast",  saveAST,   ArgFlag.Optional, "Save abstract syntax trees to JSON (for use in JsonViewer)" ));
		mixin(defineArg!(cmd, "astd", astDir,    ArgFlag.Optional, "JSON AST output directory (implies -ast) (default: curr dir)" ));
	}
	
	enum helpHeader = 
		helpInfoHeader("GenDocs", "2010-2011 Nick Sabalausky") ~
		"\n\n" ~
		"Generates HTML documentation.\n";

	// Returns: Should processing proceed? If false, the program should exit.
	private bool parse(string[] args)
	{
		const string sampleUsageMsg = "Sample Usage: goldie-gendocs docssrc/docs.tmpl\n";
		cmd.parse(args);
		if(detailhelp)
		{
			writeln(helpHeader);
			writeln(sampleUsageMsg);
			write(cmd.getDetailedUsage());
			return false;
		}
		if(!cmd.success || help)
		{
			writeln(helpHeader);
			writeln(sampleUsageMsg);
			write(cmd.getUsage(14));
			if(!help)
			{
				writeln();
				write(cmd.errorMsg);
			}
			return false;
		}

		void ensureTrailingSlash(ref string path)
		{
			// UTF-safe because '/' and '\\' are one code-unit
			if(path[$-1] != '/' && path[$-1] != '\\')
				path ~= "/";
		}
		
		if(astDir != "")
		{
			saveAST = true;
			ensureTrailingSlash(astDir);
		}
		
		//TODO*: This is using the wrong 'normalize'
		if(outDir == "")
			outDir = normalize(getExecPath()~"../docs/");
		ensureTrailingSlash(outDir);

		if(srcFile == "")
			srcFile = normalize(getExecPath()~"../docssrc/Docs.tmpl");
		
		srcDir  = dirname(srcFile);
		srcFile = basename(srcFile);
		
		return true;
	}
}
