"""
A core to delete files from theospectra (and possibly others).
"""

import os

from gavo import api
from gavo import svcs

class Core(svcs.Core):
	"""is a custom core trying to delete previously uploaded data.
	"""
	inputTableXML = """
		<inputTable>
			<inputKey name="spectrumid" type="text"
					tablehead="Spectrum id"/>
		</inputTable>"""

	outputTableXML = """
		<outputTable>
			<outputField name="numberAffected" tablehead="Affected" type="integer"
				verbLevel="1" required="True"/>
		</outputTable>"""
		
	def _unlinkWithIds(self, idsToDelete):
		# we used to iterate over all the sources here to be sure we got 'em
		# all, but that would take a long time now that there's so many files.
		# So, instead we're playing it cool and we're just removing the thing
		# in uploads.
		for id in idsToDelete:
			try:
				os.unlink(self.rd.getAbsPath("uploads/"+id))
			except os.error:
				# it's certainly not good that the file isn't there, but
				# I'll still not hunt for it.  Let's move to rsync uploads
				# soon.
				pass

	
	def _delete(self, spid):
		if spid.endswith(".meta"):
			spid = spid[:-5]
		spid = os.path.basename(spid)

		affected = 0
		toDelete = []
		with api.getWritableAdminConn() as conn:
			targetTable = api.TableForDef(self.rd.getById(
				self.getProperty("targetTable")), connection=conn)
			count = conn.execute(
				"DELETE FROM %s WHERE ssa_creatordid=%%(creatordid)s"%
					targetTable.tableDef.getQName(),
				{"creatordid": "ivo://tmap.iaat/"+spid})
			if count>0:
				toDelete.append(spid)
				conn.execute("DELETE FROM dc.products WHERE"
					" accref=%(accref)s",
					{"accref": "theossa/spec/upload/%s.txt"%spid})
				conn.execute("DELETE FROM dc.products WHERE"
					" accref=%(accref)s",
					{"accref": "theossa/spec/upload/%s.vot"%spid})
			affected += count
		self._unlinkWithIds(set(toDelete))
		return affected

	def run(self, service, inputTable, queryMeta):
		# Let people have filenames with extensions and all if they want.
		spid = inputTable.getParam("spectrumid")
		if spid is None:
			affected = 0
		else:
			affected = self._delete(spid)
		t = api.TableForDef(self.outputTable, rows=[
			{"numberAffected": affected}])
		return t


if __name__=="__main__":
	from gavo import api
	rd = api.getRD("theossa/q")
	c = rd.getById("delete_core")
	print(c._delete("0050000_4.22_7.375E-01_2.493E-01_2.365E-03_03000-55000_2017-10-13_10_13_21.meta"))
