#!/usr/bin/python

import json
from hashlib import sha256
from urllib2 import urlopen
from urllib import quote

# https://github.com/alecgorge/jsonapi/wiki/Analyzing-the-jsonapi-request-and-response-format
# http://alecgorge.github.io/jsonapi/
# NEW API USAGE: http://mcjsonapi.com/apidocs/

def jsonapi(params, methodData, debug=False):
    """Pull data from Bukkit/Spigot Plugin, JSONAPI, to be further used later on"""
    sendData = []
    for method, methodArgs in methodData.iteritems():
        sendData.append({
            "name": method,
            "key": sha256(params['username'] + method + params['password']).hexdigest(),
            "username": params['username'],
            "arguments": methodArgs
            #"tag": "sampleTag" <-- not really used for what I do..
        })
    if debug: print json.dumps(sendData, indent=2)

    uri = 'http://{host}:{port}/api/2/call?json={data}'

    uri = uri.format(
        host=params['host'],
        port=str(params['port']),
        data=quote(json.dumps(sendData))
    )
    if debug: print uri


    data = json.loads(urlopen(uri).read())
    if debug: print json.dumps(data, indent=2)
    
    returnData = {}
    # Do some stuff with the data, make it pretty... :)
    for method in data:
        if method['is_success']:
            returnData[str(method['source'])] = method['success']
        else:
            returnData[str(method['source'])] = False
    
    if len(returnData) == 1:
        for key, data in returnData.iteritems():
            return data

    return returnData

params = {
    'host': 'play.yourserver.net',
    'port': 20059,
    'username': 'admin',
    'password': 'changeme'
}

methods = {
    'server.version': [],
    'server': []
}

data = jsonapi(params, methods)
print json.dumps(data, indent=2)
