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();
		char[] 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 = m.readLine();
			
			linebuf = std.string.replace( linebuf, "<", "&lt;" );
			linebuf = 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(LOG_FORMATTED_NAME, buffer);
	}


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