# pyvo code to pull spectra for a given composition from TheoSSA
# (determining the best match to a local spectrum is left as an exercise
# to the user:-).  Here, we just see if we can pull out values in a given
# band with Teff and log_g

import urllib
import numpy as np
from astropy import table
from astropy import units as u

import pyvo


# use format=metadata to figure out the custom parameters of an
# SSA service -- we'll need these below.
ACCESS_URL = "http://dc.g-vo.org/theossa/q/ssa/ssap.xml?"
LAMBDA_INT = 100e-9


def get_matching_spectra(**constraints):
	query = pyvo.dal.ssa.SSAService(ACCESS_URL
		).create_query(**constraints)
	return query.execute()


def fetch_flux_near(url, lambda0):
	"""returns a wavelength, flux near a wavelength from a votable 
	spectrum near url.

	For simplicity, we hardcode column names; you could do a lot better 
	by exploiting more VOTable and even SDM metadata.

	lambda0 needs to be a quantity.

	And yes, for this particular use case one would rather use SODA
	"""
	spec = table.Table.read(urllib.urlopen(url).read)
	spec_loc = spec["spectral"].to("m")
	min_index = np.argmin(spec_loc-lambda0)
	return spec_loc[min_index], spec["flux"][min_index]


if __name__=="__main__":
	spectra = get_matching_spectra(
			w_Al="0.00099/0.001", w_C="0.4532/0.4534", FORMAT="votable")
	# Yeah, SSA and its utypes suck.
	spec_start_name = spectra.fieldname_with_utype(
		"ssa:Char.SpectralAxis.Coverage.Bounds.Start")
	spec_end_name = spectra.fieldname_with_utype(
		"ssa:Char.SpectralAxis.Coverage.Bounds.Stop")

	for res in spectra:
		if res[spec_start_name]<LAMBDA_INT<res[spec_end_name]:
			# we have data near what we're interested in -- fetch data
			# and pull out a flux
			print(fetch_flux_near(res.getdataurl(), LAMBDA_INT*u.m))
