# Obsolete -- this kind of stuff doesn't work from within a grammar, it has
# to be a script; worse, it was far too slow.
#
# A custom grammar to fiddle together the reconstructed measurements
# that led up to USNO B.  Used in redux/reconstructedObs
#
# This needs usnob.platecorrs to be gavoimp'd beforehand, because it
# reads that data and uses functions defined in there.

from gavo import sqlsupport
from gavo.parsing import customgrammar

class Grammar(customgrammar.UserGrammar):
	def __init__(self, parentDD, userAttrs, initvals):
		super(Grammar, self).__init__(parentDD, userAttrs, initvals)
		self._getCorrections()
	
	def _getCorrections(self):
		"""gets the plate corrections from the database.
		"""
		with sqlsupport.AdhocQuerier() as s:
			self.corrs = {}
			for survey, plate, da, dd in s.query("SELECT * from usnob.platecorrs"):
				self.corrs[survey, plate] = 0.1, 0.2 #da, dd
		
	def _getDocdict(self, parseContext):
		return {}
	
	fieldNames = {
		"A": ("b1xi", "b1eta", "b1f", "b1s", "b1mag"),
		"B": ("b2xi", "b2eta", "b2f", "b2s", "b2mag"),
		"C": ("r1xi", "r1eta", "r1f", "r1s", "r1mag"),
		"D": ("r2xi", "r2eta", "r2f", "r2s", "r2mag"),
	#	"I": ("ixi", "ieta", "if", "i_s", "imag"),
		# XXX: I data not yet processed!
	}

	def _iterRows(self, parseContext):
		conn = getDBConnection("admin")
		count = 0
		for survey, field in self.corrs:
			count += 1
			if count>10:
				return
			print "\nNow processing %s %s"%(survey, field)
			da, dd = self.corrs[survey, field]
			xicol, etacol, fieldcol, surveycol, magcol = self.fieldNames[survey]
			cursor = conn.cursor()
			cursor.execute("SELECT usnob_createorigtable(%(survey)s, %(field)s,"
					" %(xicol)s, %(etacol)s, %(magcol)s, %(surveycol)s, %(fieldcol)s)",
				locals())
			cursor.execute("INSERT INTO uredux.obspos (SELECT raj2000, dej2000,"
				" alphaEp+%(da)s, deltaEp+%(dd)s, epoch, %(survey)s"
				" FROM origPos)", locals())
			cursor.execute("DROP TABLE origPos")
			conn.commit()
		if False:
			yield None


getGrammar = Grammar
