#!/usr/bin/env python

# A script showcasing the use of an ephemeris service to generate
# positions to match against the Harvard plates (DASCH) in the VO
# using TAP.  See https://blog.g-vo.org/TODO
# for human-digestible information on this.

from astropy import table
from astropy import units as u
from astropy.coordinates import SkyCoord
from astropy.time import Time
import pyvo

ephem = table.Table.read("https://vo.imcce.fr/webservices/miriade/ephemcc.php"
	"?-from=vespa&-name=c:p/encke&-ep=1941-04-01&-nbd=90&-step=1d"
	"&-observer=500&-mime=votable")

parsed = SkyCoord(ephem["ra"], ephem["dec"], unit=(u.hourangle, u.deg))
ephem["ra"] = parsed.ra.degree
ephem["dec"] = parsed.dec.degree

parsed = Time(ephem["epoch"])
ephem["epoch"] = parsed.mjd

# Throw away unnecessary columns to save on upload bandwidth
for col_name in ["target", "distance", "mv", "dist_dot", "phase",
		"elongation", "ddec", "dracosdec"]:
	del ephem[col_name]

svc = pyvo.dal.TAPService("http://dc.g-vo.org/tap")
# note that usually, you would probably query dasch.narrow_plates
# rather than dasch.plates here.  cf.
# http://blog.g-vo.org/a-data-publisher-s-diary-wide-images-in-dasch.html
res = svc.run_sync("""
	SELECT *
	FROM
		dasch.plates
		JOIN tap_upload.orbit
		ON (1=contains(point(ra, dec), s_region))
	WHERE
		1=ivo_interval_overlaps(
		  epoch, epoch,
		  t_min, t_max)""",
	uploads={"orbit": ephem})

res.to_table().write("encke-frames.vot", format="votable")

with pyvo.samp.connection() as conn:
	for dl in res.iter_datalinks():
		link = next(dl.bysemantics("#preview-image"))
		pyvo.samp.send_image_to(
			conn,
			link.access_url,
			client_name="Aladin")
