#!/usr/bin/env python3

import logging
import sys
import getpass
import json
import requests

def check(r):
        if r.status_code // 100 != 2:
            json = r.json()
            if json.get("offset"):
                print(json["code"], json["message"], json["offset"], file=sys.stderr)
            else:
                print(json["code"], json["message"], file=sys.stderr)
            sys.exit(1)

args = sys.argv
if len(args) < 3 or len(args) % 2 != 1:
    print("\nThis must have two fixed arguments: url and plugin mnemonic\nfollowed by pairs of arguments to represent the credentials. For example\n\n    ", args[0], "https://example.com:8181 db username root password guess\n", file=sys.stderr)
    sys.exit(1)
    
url = args[1]

r = requests.get(url + "/icat/version", verify=False)
check(r)
print(r.json()["version"], file=sys.stderr)

plugin = args[2]

credentials = []
for i in range (3, len(args), 2):
    key = args[i]   
    if args[i + 1] == "-":
        value = getpass.getpass()
    else:
        value = args[i + 1]
    credential = {}
    credential[key] = value
    credentials.append(credential)
    
arg = {}
arg["plugin"] = plugin
arg["credentials"] = credentials

r = requests.post(url + "/icat/session", data={'json': json.dumps(arg)}, verify=False)
check(r)
sessionId = r.json()["sessionId"]

r = requests.get(url + "/icat/session/" + sessionId, verify=False)
check(r)
print("Logged in as", r.json()["userName"], "with", r.json()["remainingMinutes"], "minutes to go")

r = requests.get(url + "/icat/entityManager", params = {"sessionId":sessionId, "query" : "SELECT g.id FROM Grouping g WHERE g.name='annoying animals'"}, verify = False)
check(r)
groupIds = r.json()
if len(groupIds): 
    print("Grouping 'annoying animals' already exist - they will be deleted")
    for groupId in groupIds:
        g = {"Grouping": {"id" : groupId}}
        r = requests.delete(url + "/icat/entityManager", params={"sessionId":sessionId, "entities" : json.dumps(g)}, verify=False)
        check(r)
        
grouping = {"name":"annoying animals"}
entity = {"Grouping" : grouping}
r = requests.post(url + "/icat/entityManager", data={"sessionId":sessionId, "entities" : json.dumps(entity)}, verify=False)
check(r)

r = requests.get(url + "/icat/entityManager", params = {"sessionId":sessionId, "query" : "SELECT g.id FROM Grouping g WHERE g.name='annoying animals'"}, verify = False)
check(r)
groupIds = r.json()

if len(groupIds) != 1:
    print("There are now", len(groupIds), "groupings instead of 1 - something is wrong", file=sys.stderr)
    sys.exit(1)
       
for groupId in groupIds:
        g = {"Grouping": {"id" : groupId}}
        r = requests.delete(url + "/icat/entityManager", params={"sessionId":sessionId, "entities" : json.dumps(g)}, verify=False)
        check(r)

r = requests.get(url + "/icat/entityManager", params = {"sessionId":sessionId, "query" : "SELECT g.id FROM Grouping g WHERE g.name='annoying animals'"}, verify = False)
check(r)
groupIds = r.json()
if len(groupIds):
    print("There are now", len(groupIds), "groupings instead of 0 - something is wrong", file=sys.stderr)
    sys.exit(1)
    
r = requests.delete(url + "/icat/session/" + sessionId, verify=False)
check(r)

print("Login, search, create, delete and logout operations were all successful.")
    

