import os
import shutil

html_start = """
<!DOCTYPE html>
<head>
	<link rel="stylesheet" type="text/css" href="/html/css/style.css"> 
</head> \n
<body> \n
\t<div id=container>\n
\t\t<div id="head_info">\n
"""
html_end = """
\t\t</div>
\t<div>
</body>
</html>
"""

def create_dir():
	report = 'report'
	if not os.path.isdir(report) or not os.path.exists(report):
		os.mkdir(report)
	else:
		shutil.rmtree(report)
		os.mkdir(report)

def writeHTMLDoc(error_links, location,  username='root'):
	print 'Creating a report ....'

	if username=='root':
		f = open('report/report.html','w')
		f.write(html_start)
		f.write('\t\t\t<p>This page is generated for the web master!</p>\n')
	else:
		username = username.split('@')[0]
		f = open('report/' + username+ '.html','w')
		f.write(html_start)
		f.write('\t\t\t<p>This page is generated for {{user_name}}!</p>\n')
	f.write('</div>')
	f.write('\t\t<div id="mini-container">\n')
	post_message = ""
	choose_div = True
	for (url, broken) in error_links.iteritems():
		if url.endswith("/"):
			url = url[:-1]
		if choose_div:
			f.write('\t<div id="parent_page1">\n')
			choose_div = False
		else:
			f.write('\t<div id="parent_page2">\n')
			choose_div = True
		f.write('\t\t<p id="parent_link">' +url + '</p>\n')
		f.write('\t\t<div id="broken_links">\n')
		f.write('\t\t<table id="broken_links_talbe"><thead><tr><th>Broken Links</th><th>Error Code</th></tr></thead><tbody>\n')
		for (brokenURL, httperr) in broken[0].iteritems():
			post_message += brokenURL + ';' + str(broken[2][brokenURL]) + '|'
			f.write('\t\t\t<tr><td>' + brokenURL + '</td><td>' + str(httperr) + '</td></tr>\n')
		for (brokenURL, urlerr) in broken[1].iteritems():
			post_message += brokenURL + ';' + str(broken[2][brokenURL]) + '|'
			f.write('\t\t\t<tr><td>' + brokenURL + '</td><td>' + str(urlerr) + '</td></tr>\n')
                print url + " " + str(location)
                f.write('\t\t</tbody></table>\n')
		f.write('\t\t</div>\n')
		f.write('\t\t<div id="form">\n')
		f.write('\t\t<div id="mock_form">\n')
		f.write('\t\t\t<form method="get" action="/mockthepage">\n')
		f.write('\t\t\t<button name="url" value="'+url+ '">See mock page!</button>\n')
		f.write('\t\t\t<input type="hidden" value="{{user_name}}" name="uname"></input>\n')
		f.write('\t\t\t<input type="hidden" value="' + str(location[url]) +'" name="location">\n')
		f.write('\t\t\t</form>\n')
		f.write('\t\t</div>\n')
		f.write('\t\t<div id="source_form">\n')
		f.write('\t\t\t<form method="post" action="/seesource/">\n')
		f.write('\t\t\t<button name="url" value="'+url+ '">View source page!</button>\n')
		f.write('\t\t\t<input type="hidden" value="'+ post_message +'" name="pointers"></input>\n')
		f.write('\t\t\t</form>\n')
		f.write('\t\t</div>\n')
		f.write('\t\t</div>\n')
		f.write('\t</div>\n')
	f.write(html_end)
	f.close()
	print 'Report created for the root user!'
