#!/usr/bin/env python

import os, sys, re
from cgitools import isOnline, cgi_token, exitWithInfo, decodeStr, script_path_url, unescape, color_th, color_td, style_tb

#print   'Content-type:   text/plain   name="test_name"\n'
#print   'Content-Disposition:   inline; filename="obj.Rdata"\n\n'  

#print "Content-Type:application/octet-stream\n"
#print "Content-Disposition:attachment;filename='test_name'\n\n"


#print "Content-Disposition: attachment;filename=test_file\n"
#print "Content-Transfer-Encoding: binary\n"
#print "Accept-Ranges: bytes\n"
#print "Content-Length: %ld\n" % os.stat(fn).st_size
#print "Connection: close\n"
#print "Content-type: application/octet-stream\n"
#print "\n");  

# need a comma after "print" to prevent extra line char - '\n'
#print "Content-Type:application/x-download\n",
#print "Content-Disposition:attachment;filename=%s\n\n" % fn,
#print open(fn, 'rb').read(), # this will append a line char anyway

if not isOnline(): exitWithInfo('Logon first please.')

request_page = os.getenv('QUERY_STRING')
if not request_page: #is None: 
	request_page = os.getenv('PATH_INFO')
	if request_page and len(request_page)>1: request_page = request_page[1:] # remove the leading slash '/'
	else: exitWithInfo('No file name offered!')

# parse pih_vars
# request_page could be request_page[?|/]:{...a_python_dict_...}  
pih_vars = {'cur_pg':0, 'rec_num':100}
if request_page:
	m = re.compile(r'^\s*(.+?)\s*:\s*(\{.+\})\s*$').match(request_page)
	if m:
		request_page = m.groups()[0]
		try:
			pih_vars = eval(unescape(m.groups()[1]))
		except:
			print cgi_token
			print m.groups()[1]
			sys.exit(0)

filename = decodeStr(request_page)

if not os.path.exists(filename): exitWithInfo('The file is not found!')

cur_pg, rec_num = pih_vars.get('cur_pg',0), pih_vars.get('rec_num', 1000)

lines = open(filename).readlines()
# remove blank lines at the begining
i = 0
for line in lines:
	if line.strip(): break
	i = i+1
if i>0: lines = lines[i:]
# remove blank lines at the end
for i in xrange(len(lines)-1, -1, -1): #range(len(lines))[::-1]
	if lines[i].strip(): break
	lines.pop()

n = len(lines)
if not n: exitWithInfo('Empty file!')
n = n-1
title = lines[0]

pg_num = n/rec_num + ( (n % rec_num) and 1 or 0 )
at_beginning = cur_pg==0 and True or False
reach_end = ((cur_pg+1)*rec_num)>=n and True or False
lines =  lines[(cur_pg*rec_num+1):((cur_pg+1)*rec_num+1)]

def repls(obj, sdic={'\n':'', '\t':'</td><td>'}):
	#return (obj.group() not in sdic) and obj.group(4)+obj.group(5) or sdic[obj.group()]
	if obj.group() == '\n': return ''
	if obj.group() == '\t': return '</td><td>'
	if obj.group(5): return obj.group(4)+obj.group(5)
	return obj.group(4)
res = re.compile(r'(\n)|(\t)|(([+-]?\b\d+\.\d{4})\d+([Ee][+-]?\d+)?\b)')  # res.sub(repls, s)

print cgi_token

print '<html><head>%s</head><body bgcolor="white">' % style_tb
print '<table class="mytb" cellspacing="0" cellpadding="5">\n'
print '<tr bgcolor="%s"><th>%s</th></tr>\n' % (color_th, title.replace('\n','').replace('\t', '</th><th>'))
#print '<tr><th>%s</th></tr>\n' % title.replace('\n','').replace('\t', '</th><th>')

#for line in file(filename):
#	print '<tr><td>%s</td></tr>\n' % line.replace('\n','').replace('\t', '</td><td>')
#map(lambda a:sys.stdout.write('<tr><td>%s</td></tr>\n' % a.replace('\n','').replace('\t', '</td><td>')), open(filename).readlines())
#map(lambda a:sys.stdout.write('<tr><td>%s</td></tr>\n' % a.replace('\n','').replace('\t', '</td><td>')), lines)
#map(lambda a:sys.stdout.write('<tr%s><td>%s</td></tr>\n' % ( (a % 2) and ' bgcolor="#F7F7F7"' or '', lines[a].replace('\n','').replace('\t', '</td><td>')) ), range(len(lines)))
#map(lambda a:sys.stdout.write('<tr%s><td>%s</td></tr>\n' % ( (a % 2) and ' bgcolor="#d2dbe7"' or 'bgcolor="white"', res.sub(repls, lines[a]) ) ), range(len(lines)))
map(lambda a:sys.stdout.write('<tr%s><td>%s</td></tr>\n' % ( (a % 2) and ' bgcolor="%s"' % color_td or ' bgcolor="white"', res.sub(repls, lines[a]) ) ), range(len(lines)))

print '</table>'

print '''
<script language='javascript'>
function goPg(pg, n) {window.location.href="%s/viewFile?%s:{'cur_pg':" + pg + ",'rec_num':" + n + "}"}
</script>
''' % (script_path_url, request_page)

if not (at_beginning and reach_end): 
	pgstr = []
	if not at_beginning: 
		#pgstr.append("""<a href="%s/viewFile?%s:{'cur_pg':%d,'rec_num':%d}"><input type='button' value=First></a>""" % (script_path_url, request_page, 0, rec_num))
		#pgstr.append("""<a href="%s/viewFile?%s:{'cur_pg':%d,'rec_num':%d}"><input type='button' value=Previous></a>""" % (script_path_url, request_page, cur_pg-1, rec_num))
		pgstr.append("""<input type='button' value=First onClick="goPg(%d, %d)">""" % (0, rec_num))
		pgstr.append("""<input type='button' value=Previous onClick="goPg(%d, %d)">""" % (cur_pg-1, rec_num))
	if not reach_end:
		#pgstr.append("""<a href="%s/viewFile?%s:{'cur_pg':%d,'rec_num':%d}"><input type='button' value=Next></a>""" % (script_path_url, request_page, cur_pg+1, rec_num))
		#pgstr.append("""<a href="%s/viewFile?%s:{'cur_pg':%d,'rec_num':%d}"><input type='button' value=Last></a>""" % (script_path_url, request_page, n/rec_num - ((not (n % rec_num)) and 1 or 0), rec_num))
		pgstr.append("""<input type='button' value=Next onClick="goPg(%d, %d)">""" % (cur_pg+1, rec_num))
		pgstr.append("""<input type='button' value=Last onClick="goPg(%d, %d)">""" % (n/rec_num - ((not (n % rec_num)) and 1 or 0), rec_num))
	pgstr.append('&nbsp;&nbsp;%d in %d pages' % (cur_pg+1, pg_num))
	print '<p>','&nbsp;&nbsp;'.join(pgstr)

print '</body>'
print '</html>'
