#!/usr/bin/python3
"""G.Landais (CDS) 2022-jun-17
   query IMCCE (from sesame)
"""

import getopt
import sys

if sys.version_info < (3, 0):
    import urllib as ulib
    import urllib as uparse
else:
    import urllib.request as ulib
    import urllib.parse as uparse

import json
import os

VERBOSE = False


def __debug(s):
    if VERBOSE is False: return
    sys.stderr.write("(debug) "+str(s)+"\n")
def __error(s):
    sys.stderr.write("(error) "+str(s)+"\n")

IMCCE_URL = "https://api.ssodnet.imcce.fr/quaero/1/sso"


def IMCCEResolver(object):
    """execute (remote URL query) the IMCCE resolver
       :param object: target_name
       :return: JSON Object
    """
    try:
        url = f"{IMCCE_URL}?q={object}"
        __debug(url)
        handler = ulib.urlopen(url)
        return json.loads(handler.read().decode('utf-8'))
    except Exception as e:
        __error("ERROR IMCCE:"+str(e))
        json_error = {"error":str(e),
                      "status": -1,
                      "name":object
                      }
        return json.loads(json.dumps(json_error))


def __getValueFromKey(jsonkey, json):
    """Get the value of a json key
       :param jsonkey: json key splitted by /
       :param json: JSONObject
       :return: the value
    """
    keys = jsonkey.split('/')
    obj = json

    for key in keys:
        if key not in obj: 
            raise Exception("key "+jsonkey+" not found")
        obj = obj[key]

    return obj


def json2Parfile(json, prompt, target="solar_system"):
    """Transform json 2 parfile format
       :param json: JSONObject
       :param prompt: the prompt
       :param target: input target
       :return: parfile string
    """
    data = __getValueFromKey("data", json)
    if data is None or len(data)==0:
        __error("IMCCE returns no data")
        return "%J no_data"

    out = "%%<IMCCE>\n"
    out += f"{target}\t!=1=\n=1/1\t! I I.0 C\n"
    out += f"%J {target}\n"
    for rec in data:
        if "name" in rec:
            name = rec["name"]
            out += f"%I.0  {name}\n"
            if "type" in rec:
                out += f"%C {rec['type']}"
                if "class" in rec:
                    cnames = rec['class']
                    if len(cnames) > 0:
                        cnames = ",".join(cnames)
                        out += f" # {cnames}"
                
                out += "\n"
    out += "%%</IMCCE>\n" 
    return out
     

def Input(prompt=None):
    if sys.version_info < (3, 0):
        if prompt is None:
            return raw_input().strip()
        else:
            return raw_input(prompt).strip()
    if prompt is None:
        return input().strip()
    else:
        return input(prompt).strip()


if __name__ == "__main__":
    try:
        __opt, __args = getopt.getopt(sys.argv[1:], 'vp:', ["help"])
    except getopt.GetoptError as err:
        sys.stderr.write("(error) "+str(err)+"\n")
        sys.exit(1)

    Prompt = None
    for __o, __a in __opt:
        if __o in ("-h","help"):
            help("__main__")
            sys.exit(0)
        elif __o == '-v':
            VERBOSE = True
        elif __o == '-p':
            Prompt = __a
        else:
           __debug("option "+__o+" is not available => skipped")
           help("__main__")
           sys.exit(0)


    __object = []
    if os.isatty(0) is False:
        __debug("read from stdin")

        while True:
            try:
                if Prompt is None: Prompt= ">"
                print (Prompt)
                line = Input().strip()
                __debug(line)
            except:
                break
            if line[0]=='#': continue
            __jsonobject = IMCCEResolver(line)
            __debug("get "+json.dumps(__jsonobject))

            try:
                print (json2Parfile(__jsonobject, Prompt, line))
            except Exception as err:
                __error(err)
                print ("#Not Found {0:s} ({1:s})".format(__o,str(err)))
        sys.exit(0)

    elif Prompt is not None:
        while True:
            line = Input(Prompt).strip()
            if line == "": break
            __object.append(line.replace(Prompt,""))

    else:
        
        if len(sys.argv) < 2: 
            help("__main__")
            sys.exit(1)
    
        __object.append(sys.argv[-1])

    for __o in __object:
        __debug("execute IMCCE query "+__o)
        __jsonobject = IMCCEResolver(__o)
        __debug("get "+json.dumps(__jsonobject))

        try:
            print (json2Parfile(__jsonobject, None, __o))
        except Exception as err:
            __error(err)
            print ("#Not Found {0:s} ({1:s})".format(__o,str(err)))
