from js import XMLHttpRequest, Blob

import json
import base64
import cloudpickle


def get(get_id):
    enc = base64.standard_b64encode(get_id).decode()
    body = json.dumps({"id": enc})
    req = XMLHttpRequest.new()
    req.open("POST", "/api/get", False)
    blob = Blob.new([body], {type: 'application/json'})
    req.send(blob)
    out = json.loads(req.response)
    return out


def put(obj):
    data = cloudpickle.dumps(obj)
    enc = base64.standard_b64encode(data).decode()
    body = json.dumps({"data": enc})
    req = XMLHttpRequest.new()
    req.open("POST", "/api/put", False)
    blob = Blob.new([body], {type: 'application/json'})
    req.send(blob)
    out = json.loads(req.response)
    out_id = base64.standard_b64decode(out["id"])
    return out_id


def schedule(task):
    body = json.dumps(task)
    req = XMLHttpRequest.new()
    req.open("POST", "/api/schedule", False)
    blob = Blob.new([body], {type: 'application/json'})
    req.send(blob)
    out = json.loads(req.response)
    out_id = base64.standard_b64decode(out["return_id"])
    return out_id
