"""
Get a little sample from all tables in tap_schema.tables of a server.
"""

import os
import random
import sys

from gavo import votable
from gavo.votable import tapquery


ENDPOINT_URL = os.environ.get("ENDPOINT_URL",
	"http://dc.zah.uni-heidelberg.de/tap")


def getTables():
	data, metadata = votable.load(tapquery.ADQLSyncJob(ENDPOINT_URL,
		"SELECT table_name from tap_schema.tables").run().openResult())
	tables = [r[0] for r in data]
	random.shuffle(tables)
	return tables


def sampleOne(tableName):
	sys.stdout.write("%s...    "%tableName)
	sys.stdout.flush()
	try:
		data, metadata = votable.load(tapquery.ADQLSyncJob(ENDPOINT_URL,
			"SELECT TOP 100 * from %s"%tableName).run().openResult())
		if len(list(data))==100:
			sys.stdout.write("\r\x1bK")
			sys.stdout.flush()
		else:
			sys.stdout.write(" %d records.\n"%len(list(data)))
	except Exception as ex:
		sys.stdout.write(" fail (%s)\n"%sys.exc_info()[0].__name__)


if __name__=="__main__":
	for tableName in getTables():
		sampleOne(tableName)
