#!/usr/bin/env python3
import argparse
import os
import requests
from nacl.signing import SigningKey
from json import dumps


class ToolshedApi:
    user = None
    host = None
    signing_key = None

    def __init__(self, user, host, key):
        if host is None:
            raise ValueError("TOOLSHED_HOST environment variable not set")

        if user is None:
            raise ValueError("TOOLSHED_USER environment variable not set")

        if key is None:
            raise ValueError("TOOLSHED_KEY environment variable not set")

        if len(key) != 64:
            raise ValueError("TOOLSHED_KEY must be 64 hex characters")

        signing_key = SigningKey(bytes.fromhex(key))

        self.user = user
        self.host = host
        self.signing_key = signing_key

    def get(self, target):
        url = "http://" + self.host + target
        signed = self.signing_key.sign(url.encode('utf-8'))
        signature = signed.signature.hex()
        response = requests.get(url, headers={"Authorization": "Signature " + self.user + ":" + signature})
        return response.json()

    def post(self, target, data):
        url = "http://" + self.host + target
        json = dumps(data)
        signed = self.signing_key.sign(url.encode('utf-8') + json.encode('utf-8'))
        signature = signed.signature.hex()
        response = requests.post(url, headers={"Authorization": "Signature " + self.user + ":" + signature}, json=data)
        return response.json()


def main():
    host = os.environ.get('TOOLSHED_HOST')
    user = os.environ.get('TOOLSHED_USER')
    key = os.environ.get('TOOLSHED_KEY')

    parser = argparse.ArgumentParser(description='Toolshed API client')
    parser.add_argument('--host', help='Toolshed host')
    parser.add_argument('--user', help='Toolshed user')
    parser.add_argument('--key', help='Toolshed key')
    parser.add_argument('cmd', help='Command')
    args = parser.parse_args()

    if args.host is not None:
        host = args.host

    if args.user is not None:
        user = args.user

    if args.key is not None:
        key = args.key

    api = ToolshedApi(user, host, key)

    if args.cmd == 'getinventory':
        inv = api.get("/api/inventory_items/")
        print(inv)
    elif args.cmd == 'additem':
        inv = api.post("/api/inventory_items/", {"name": "test"})
        print(inv)
    else:
        print("Unknown command: " + args.cmd)


if __name__ == '__main__':
    main()
