#ifdef flagGUI
#include <CtrlLib/CtrlLib.h>
#include <ide/Browser/Browser.h>

#include "Functions4U/Functions4U.h"
#include "GatherTpp.h"

NAMESPACE_UPP

struct ScanTopicIterator : RichText::Iterator {
	VectorMap<String, String> *reflink;
	String link;
	StaticCriticalSection reflink_lock;
	
	ScanTopicIterator(VectorMap<String, String> *reflink) : reflink(reflink) {};
	virtual bool operator()(int pos, const RichPara& para)
	{
		if(!IsNull(para.format.label)) 
			reflink->Add(para.format.label, link);
		return false;
	}
};

void GatherTpp::GatherRefLinks(const char *upp)
{
	for(FindFile pff(AppendFileName(upp, "*.*")); pff; pff.Next()) {
		if(pff.IsFolder()) {
			String package = pff.GetName();
			String pdir = AppendFileName(upp, package);
			TopicLink tl;
			tl.package = package;
			for(FindFile ff(AppendFileName(pdir, "*.tpp")); ff; ff.Next()) {
				if(ff.IsFolder()) {
					String group = GetFileTitle(ff.GetName()	);
					tl.group = group;
					String dir = AppendFileName(pdir, ff.GetName());
					for(FindFile ft(AppendFileName(dir, "*.tpp")); ft; ft.Next()) {
						if(ft.IsFile()) {
							String path = AppendFileName(dir, ft.GetName());
							tl.topic = GetFileTitle(ft.GetName());
							String link = TopicLinkString(tl);
							ScanTopicIterator sti(&reflink);
							sti.link = link;
							ParseQTF(ReadTopic(LoadFile(path))).Iterate(sti);
						}
					}
				}
			}
		}
	}
}

struct GatherLinkIterator : RichText::Iterator {
	VectorMap<String, String> *reflink;
	Index<String> link;

	GatherLinkIterator(VectorMap<String, String> *reflink) : reflink(reflink) {};
	virtual bool operator()(int pos, const RichPara& para)
	{
		for(int i = 0; i < para.GetCount(); i++) {
			String l = para[i].format.link;
			if(!IsNull(l)) {
				if(l[0] == ':') {
					int q = reflink->Find(l);
					if(q < 0)
						q = reflink->Find(l + "::class");
					if(q < 0)
						q = reflink->Find(l + "::struct");
					if(q < 0)
						q = reflink->Find(l + "::union");
					if(q >= 0)
						l = (*reflink)[q];
				}
				link.FindAdd(Nvl(reflink->Get(l, Null), l));
			}
		}
		return false;
	}
};

String GetIndexTopic(String file)
{
	String topic = GetFileTitle(file);
	String folder = GetFileFolder(file);
	String topicLocation = GetFileTitle(folder);
	folder = GetUpperFolder(folder);
	topicLocation = GetFileTitle(folder) + "/" + topicLocation;

	return "topic://" + topicLocation + "/" + topic;
}

int CharFilterLbl(int c)
{
	return IsAlNum(c) ? c : '.';
}

void QtfAsPdf(PdfDraw &pdf, const char *qtf)
{
	RichText txt = ParseQTF(qtf);
	Size page = Size(3968, 6074); 
	UPP::Print(pdf, txt, page);
}

/*
Htmls RoundFrame(Htmls data, String border, Color bg)
{
	return HtmlPackedTable().BgColor(bg).Width(-100)
	          .Attr("style", "border-style: solid; border-width: 1px; border-color: #" + border + ";")
	       / HtmlLine() / data;
}
*/

bool ContainsAt(const String &source, const String &pattern, int pos)
{
	return    pos >= 0
	       && pos + pattern.GetLength() <= source.GetLength()
	       && 0 == memcmp(source.Begin() + pos, pattern.Begin(), pattern.GetLength());
}

bool StartsWith(const String &source, const String &pattern)
{
	return ContainsAt(source, pattern, 0);
}

bool EndsWith(const String &source, const String &pattern)
{
	return ContainsAt(source, pattern, source.GetLength() - pattern.GetLength());
}

String GatherTpp::QtfAsHtml(const char *qtf, Index<String>& css,
                 const VectorMap<String, String>& links,
                 const VectorMap<String, String>& labels,
                 const String& outdir, const String& fn)
{
	return EncodeHtml(ParseQTF(qtf), css, links, labels, outdir, fn, Zoom(8, 40), escape, 40);
}

String GetText(const char *s)
{
	return GetTopic(s).text;
}

void GatherTpp::ExportPage(int i, String htmlFolder, String keywords)
{
	Index<String> css;
	String path = links.GetKey(i);
	
	String text = GetText(path);
	
	String qtflangs;	
	String strlang;

	String page = tt[i];
	page = QtfAsHtml(page, css, links, labels, htmlFolder, links[i]);

/*	
	Color paper = SWhite;
	Color bg = Color(210, 217, 210);

	Htmls html;
	html << 
		HtmlPackedTable().Width(-100) /
		   	HtmlLine().ColSpan(3)  +
		HtmlPackedTable().Width(-100) / (
			HtmlLine().ColSpan(3).BgColor(bg).Height(6) / "" +
			HtmlRow() / (
				HtmlTCell().Width(-100).BgColor(bg) / (
					RoundFrame(page , "6E89AE;padding: 10px;", White)
				)
			)
		);
*/
	String topicTitle = tt.GetKey(i);
	String pageTitle = tt[i].title;
	if(IsNull(pageTitle))
		pageTitle = title;
/*
	if(StartsWith(topicTitle, "examples$"))
		pageTitle = "Demos / " + pageTitle;
	else if(StartsWith(topicTitle, "reference$"))
		pageTitle = "Examples / " + pageTitle;
*/
	if(pageTitle != title)
		pageTitle << " :: " << title;
/*
	Htmls content =
	    "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" +
		HtmlHeader(pageTitle, AsCss(css) +
			"a.l1         { text-decoration:none; font-size: 8pt; font-family: sans-serif; "
			              "font-weight: normal; }\n"
			"a.l1:link    { color:#000000; }\n"
			"a.l1:visited { color:#000080; }\n"
			"a.l1:hover   { color:#9933CC; }\n"
			"a.l1:active  { color:#000000; }\n"
			"a.l2         { text-decoration:none; font-size: 12pt; font-family: sans-serif; "
			              "font-variant: small-caps; }\n"
			"a.l2:link    { color:#0066FF; }\n"
			"a.l2:visited { color:#FF6600; }\n"
			"a.l2:hover   { color:#BC0624; }\n"
			"a.l2:active  { color:#BC0024; }\n",
			"<META NAME=\"keywords\" "
			"CONTENT=\"" + keywords + "\">"
	        "<META name=\"robots\" content=\"index,follow\">"
		)
	    .BgColor(bg)
	    .Alink(Red).Link(Black).Vlink(Blue)
	    / html;
*/	    

	SaveFile(AppendFileName(htmlFolder, links[i]),
	    String().Cat() <<
		"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"
		"<HTML>"
		"<HEAD>"
		"<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=utf-8\">"
		"<META NAME=\"Generator\" CONTENT=\"U++ HTML Package\">"
		"<TITLE>" << pageTitle << "</TITLE>"
		"<STYLE TYPE=\"text/css\"><!--"
		<< AsCss(css) << "a.l1         { text-decoration:none; font-size: 8pt; font-family: sans-serif; font-weight: normal; }"
		"a.l1:link    { color:#000000; }"
		"a.l1:visited { color:#000080; }"
		"a.l1:hover   { color:#9933CC; }"
		"a.l1:active  { color:#000000; }"
		"a.l2         { text-decoration:none; font-size: 12pt; font-family: sans-serif; font-variant: small-caps; }"
		"a.l2:link    { color:#0066FF; }"
		"a.l2:visited { color:#FF6600; }"
		"a.l2:hover   { color:#BC0624; }"
		"a.l2:active  { color:#BC0024; }"
		"-->"
		"</STYLE>"
		"<META NAME=\"keywords\" CONTENT=\"" << keywords << "\"><META name=\"robots\" content=\"index,follow\"></HEAD><BODY BGCOLOR=\"#D2D9D2\" ALINK=\"#800000\" LINK=\"#000000\" VLINK=\"#000080\"><TABLE BORDER=\"0\" CELLSPACING=\"0\" CELLPADDING=\"0\" WIDTH=\"100%\"><TR><TD COLSPAN=\"3\"></TD>"
		"</TR>"
		"</TABLE>"
		"<TABLE BORDER=\"0\" CELLSPACING=\"0\" CELLPADDING=\"0\" WIDTH=\"100%\"><TR><TD COLSPAN=\"3\" BGCOLOR=\"#D2D9D2\" HEIGHT=\"6\"></TD>"
		"</TR>"
		"<TR><TD VALIGN=\"TOP\" WIDTH=\"100%\" BGCOLOR=\"#D2D9D2\"><TABLE BORDER=\"0\" CELLSPACING=\"0\" CELLPADDING=\"0\" BGCOLOR=\"#FFFFFF\" WIDTH=\"100%\" style=\"border-style: solid; border-width: 1px; border-color: #6E89AE;padding: 10px;;\"><TR>"
		"<TD>" << page << "</TD>"
		"</TR>"
		"</TABLE>"
		"</TD>"
		"</TR>"
		"</TABLE>"
		"</BODY>"
	);
}

String GatherTpp::TopicFileName(const char *topic)
{
	TopicLink tl = ParseTopicLink(topic);
	String file = AppendFileName(dir, AppendFileName(tl.group + ".tpp", tl.topic + ".tpp"));
	if (FileExists(file))
		return file;
		
	for (int i = 0; i < rootFolders.GetCount(); ++i) {
		if (rootFolders[i] != dir) {
			file = AppendFileName(rootFolders[i], AppendFileName(tl.package , AppendFileName(tl.group + ".tpp", tl.topic + ".tpp")));
			if (FileExists(file))
				return file;		
		}
	}
	return "";
}

String TopicFileNameHtml(const char *topic)
{
	TopicLink tl = ParseTopicLink(topic);
	return tl.group + "$" + tl.package+ "$" + tl.topic + ".html";
}

String GatherTpp::GatherTopics(const char *topic, String& title)
{
	int q = tt.Find(topic);
	if(q < 0) {
		Topic p = ReadTopic(LoadFile(TopicFileName(topic)));
		title = p.title;
		String t = p;
		if(IsNull(t)) 
			return "index.html";
		tt.Add(topic) = p;
		GatherLinkIterator ti(&(reflink));
		ParseQTF(t).Iterate(ti);
		for(int i = 0; i < ti.link.GetCount(); i++) {
			String dummy;
			GatherTopics(ti.link[i], dummy);
		}
	} else 
		title = tt[q].title;
	return TopicFileNameHtml(topic);
}


String GatherTpp::GatherTopics(const char *topic)
{
	String dummy;
	return GatherTopics(topic, dummy);
}

bool GatherTpp::Load(String indexFile, Gate2<int, int> progress) {
	indexTopic = GetIndexTopic(indexFile);
	for (int i = 0; i < rootFolders.GetCount(); ++i) {
		if (progress(i+1, rootFolders.GetCount()))
			return false;
		dir = rootFolders[i];
		
		if (!DirectoryExists(dir)) 
			return false;

		GatherRefLinks(dir);
		
		if (i == 0)
			GatherTopics(indexTopic);
	}
	return true;
}

bool GatherTpp::MakeHtml(const char *folder, Gate2<int, int> progress) {
	DeleteFolderDeep(folder);
	DirectoryCreate(folder);

	for(int i = 0; i < tt.GetCount(); i++) {
		String topic = tt.GetKey(i);
		links.Add(topic, topic == indexTopic ? "index.html" :
		                 memcmp(topic, "topic://", 8) ? topic : TopicFileNameHtml(topic));
	}
	for(int i = 0; i < reflink.GetCount(); i++) {
		String l = reflink.GetKey(i);
		String lbl = Filter(l, CharFilterLbl);
		String f = links.Get(reflink[i], Null) + '#' + lbl;
		links.Add(l, f);
		static const char *x[] = { "::struct", "::class", "::union" };
		for(int ii = 0; ii < 3; ii++) {
			String e = x[ii];
			if(EndsWith(l, e)) {
				links.Add(l.Mid(0, l.GetLength() - e.GetLength()), f);
			}
		}
		labels.Add(l, lbl);
	}

	for(int i = 0; i < tt.GetCount(); i++) {
		if (progress(i+1, tt.GetCount()))
			return false;
		ExportPage(i, folder);
	}
	return true;
}

bool GatherTpp::MakePdf(const char *filename, Gate2<int, int> progress) {
	PdfDraw pdf;
	for(int i = 0; i < tt.GetCount(); i++) {
		if (progress(i+1, tt.GetCount()))
			return false;
		bool dopdf = true;
		for (int j = 0; j < i; ++j) {
			if (tt[j].text == tt[i].text) {
				dopdf = false;
				break;
			}
		}
		if (dopdf)
			QtfAsPdf(pdf, tt[i]);
	}
	SaveFile(filename, pdf.Finish());
	return true;	
}

int GatherTpp::FindTopic(const String name) {
	return tt.Find(name);
}

Topic &GatherTpp::GetTopic(int id) {
	return tt[id];
}

Topic &GatherTpp::AddTopic(const String name) {
	return tt.Add(name);
}

END_UPP_NAMESPACE

#endif