from urllib3 import HTTPSConnectionPool
import urllib3
from urllib3.util import Timeout
import json

def printEntry(text, bold=False):
    inner = r"\td{" + text.replace('%', "\\%").replace('<', '$<$') + "}" 
    return r"\textbf{" + inner + "}" if bold else inner


def makeTable(vals):
    print(r"\begin{tabular}{|l||r|r|r||r|r|r|r|r|r|} \hline")
    print(r"\thh{Name}     & \textbf{\th{15pt}{\# Tr.}} & \th{15pt}{\# S} & \th{15pt}{\# P} & \th{20pt}{Direct} & \th{20pt}{Reified}  & \th{20pt}{Type}& \th{20pt}{Label} & \th{20pt}{Desc.} & \th{20pt}{Meta}  \\ \hline \hline")

    sortedVals = [(key, vals[key]) for key in vals]
    sortedVals.sort(key=lambda x: x[1][1])
    for (kg, query_name), valsAndOrder in sortedVals:

        entries = []
        row = valsAndOrder[0]

        def f(key, i):
            if key in row:
                return printEntry(row[key][i])
            else:
                return printEntry(r"{\small\,\makebox[6pt][l]{--}}")
        entries.append(printEntry(r"\examplequeryhref{" + query_name + r"}{" + kg +'}'))
        entries.append(printEntry(row["num triples"][0], True))
        entries.append(printEntry(row["num subjects"][0]))
        entries.append(printEntry(row["num predicates"][0]))
        entries.append(f("normal",1))
        entries.append(f("reified",1))
        entries.append(f("type",1))
        entries.append(f("label",1))
        entries.append(f("description",1))
        entries.append(f("meta",1))
        print(" & ".join(entries))
        print(r"\\ \hline")

    print("\end{tabular}")



def format_count(count):
    count = int(count)
    if count > 1000000000:
        return "{:.1f}B".format(count / 1000000000.0)
    elif count > 1000000:
        return "{:.0f}M".format(count / 1000000.0)
    elif count > 1000:
        return "{:.0f}K".format(count / 1000.0)
    return str(count)

def format_percent(perc):
    perc = float(perc);
    return "{:.1f}%".format(round(perc, 1))
    


j = None
with open("queries.json", 'r') as f:
    j = json.load(f)

http = urllib3.PoolManager()
results = {}
for row in j:
    if not row.startswith("statistics"):
        continue
    url = "https://qlever.cs.uni-freiburg.de/api/" + j[row]["kg"]
    params = {"query":j[row]["query"] }
    resp = http.request("GET", url, fields=params)
    if resp.status == 200:
        res = json.loads(resp.data.decode('utf-8'))['results']['bindings'];
        vals = {}
        for r in res:
            cat = r['category']['value']
            num = format_count(r['num_total']['value'])
            perc = format_percent(r['percent']['value']) if 'percent' in r else "nan"
            vals[cat]= (num, perc, j[row]["order"])
        results[(j[row]["kg-name"], row)] = vals, j[row]["order"]
        print (vals)
makeTable(results)


