module yamalib.log.logformatter;

private import std.stream;
private import std.string;
private import y4d_aux.lineparser;
private import y4d_aux.filesys;
private import y4d_aux.widestring;
private import yamalib.log.log;

/// ログをフォーマットして出力します
class LogFormatter {

	/// ログ情報を受け取り、フォーマットして出力します
	static void createFormattedLog(void[] memory) {
		ubyte[] mem = cast(ubyte[])memory;
		std.stream.MemoryStream m = new std.stream.MemoryStream(mem);
		LineParser lp = new LineParser();
		auto buffer = TAG_HTML_S;
		buffer ~= TAG_TITLE_SE;
		buffer ~= TAG_BODY_S;
		buffer ~= "<BASEFONT color=White face=\"" ~ y4d_aux.widestring.toMBS(cast(char[])"ＭＳ ゴシック") ~ "\">";
		
		while (!m.eof) {
			char[] linebuf = cast(char[]) m.readLine();
			
			linebuf = cast(char[]) std.string.replace( linebuf, "<", "&lt;" );
			linebuf = cast(char[]) std.string.replace( linebuf, ">", "&gt;" );

			if ( -1 != std.string.find( linebuf, Log.LOG_WARN ) ) {
				buffer ~= FONT_WARN_S ~ linebuf ~ FONT_END ~ TAG_BR;
			} else if ( -1 != std.string.find( linebuf, Log.LOG_ERROR ) ) {
				buffer ~= FONT_ERROR_S ~ TAB_B_S ~ linebuf ~ TAB_B_E ~ FONT_END ~ TAG_BR;
			} else if ( -1 != std.string.find( linebuf, Log.LOG_LOOK ) ) {
				buffer ~= FONT_LOOK_S ~ TAB_U_S ~ linebuf ~ TAB_U_E ~ FONT_END ~ TAG_BR;
			} else {
				buffer ~= FONT_ETC_S ~ linebuf ~ FONT_END ~ TAG_BR;
			}
		}
		
		buffer ~= TAG_BODY_E;
		buffer ~= TAG_HTML_E;

		FileSys.write(cast(char[]) LOG_FORMATTED_NAME, cast(void[]) buffer);
	}


private:
	// 出力ログファイル名
	static const char[] LOG_FORMATTED_NAME = "log.html";
	static const char[] FONT_WARN_S = "<font color=yellow>";
	static const char[] FONT_ERROR_S = "<font color=red>";
	static const char[] FONT_ETC_S = "<font color=white>";
	static const char[] FONT_LOOK_S = "<font color=blue>";
	static const char[] FONT_END = "</font>";
	static const char[] TAG_BR = "<BR>\n";
	static const char[] TAG_HTML_S = "<HTML>";
	static const char[] TAG_HTML_E = "</HTML>";
	static const char[] TAG_BODY_S = "<BODY bgcolor='Black'>";
	static const char[] TAG_BODY_E = "</BODY>";
	static const char[] TAG_TITLE_SE = "<TITLE>LOG</TITLE>";
	static const char[] TAB_B_S = "<B>";
	static const char[] TAB_B_E = "</B>";
	static const char[] TAB_U_S = "<U>";
	static const char[] TAB_U_E = "</U>";
//	static char[] TAG_BASEFONT = "<BASEFONT face=\"" ~ y4d_aux.widestring.toMBS(cast(char[])"ＭＳ ゴシック") ~ "\">";
	
}