"""
Make an ASCII dump of the PPMXL.

The dump is written to stdout.  To make a new dump, go to the ppmxl resource
directory and say

python bin/mkasc.py | gzip > static/dump-new.gz

and rename dump-new.gz to dump-for-web.gz when done.
"""

from gavo import api
from gavo import base

formatsByName = {
	"ipix": "%d",
	"raj2000": "%.6f",
	"dej2000": "%.6f",
	"e_raepRA": "%.2e",
	"e_deepDE": "%.2e",
	"pmRA": "%.4e",
	"pmDE": "%.4e",
	"e_pmDE": "%.2e",
	"e_pmRA": "%.2e",
	"nobs": "%d",
	"epRA": "%.2f",
	"epDE": "%.2f",
	"Jmag": "%.3f",
	"e_Jmag": "%.3f",
	"Hmag": "%.3f",
	"e_Hmag": "%.3f",
	"Kmag": "%.3f",
	"e_Kmag": "%.3f",
	"b1mag": "%.2f",
	"b2mag": "%.2f",
	"r1mag": "%.2f",
	"r2mag": "%.2f",
	"imag": "%.2f",
	"flags": "%d",
	"magSurveys": "%s",
	"vickers_pmra": "%.4e",
	"vickers_pmde": "%.4e",
}


def makeStringifyer():
	tableDef = api.getRD("ppmxl/q").getById("main")
	formats = []
	for colInd, col in enumerate(tableDef):
		formats.append((colInd, formatsByName[col.name]))
	def formatItems(rec):
		items = []
		for colInd, fmt in formats:
			if fmt:
				val = rec[colInd]
				if val is None:
					items.append("None")
				else:
					items.append(fmt%val)
		return "|".join(items)
	return formatItems


def main():
	dumpRow = makeStringifyer()
	conn = base.getDBConnection("trustedquery")
	# name the cursor to keep psycopg from pulling it all into RAM
	cursor = conn.cursor("foo")
	cursor.execute("SELECT * FROM ppmxl.main") # LIMIT 20000")
	while True:
		rows = cursor.fetchmany(500)
		if not rows:
			break
		for row in rows:
			print dumpRow(row)


if __name__=="__main__":
	#import cProfile as profile
	#profile.run("main()", "dumping.profile")
	main()
