# plugin/external/odoo/odoo-json-test.py
# test run with odoo 16: python odoo-json-test.py

import json
import random
import urllib.request

HOST = 'localhost' # 'localhost'
PORT = 8072 # 8069
DB = 'odoo17'
USER = 'admin'
PASS = 'admin'

def json_rpc(url, method, params):
    data = {
        "jsonrpc": "2.0",
        "method": method,
        "params": params,
        "id": random.randint(0, 1000000000),
    }
    req = urllib.request.Request(url=url, data=json.dumps(data).encode(), headers={
        "Content-Type":"application/json",
    })
    print("Created new call with url: %s" % req.get_method() + " " + req.get_full_url())
    print("  header items: %s" % req.header_items())
    print("  data: %s" % req.data)
    # print(json.dumps(req, indent=2))
    reply = json.loads(urllib.request.urlopen(req).read().decode('UTF-8'))
    if reply.get("error"):
        raise Exception(reply["error"])
    # return reply
    return reply["result"]

def call(url, service, method, *args):
    return json_rpc(url, "call", {"service": service, "method": method, "args": args})

# log in the given database
url = "http://%s:%s/jsonrpc" % (HOST, PORT)
# url = "https://odoo.capacic.com/xmlrpc/2/"
uid = call(url, "common", "login", DB, USER, PASS)

# create a new note
args = {
    'color': 8,
    'memo': 'This is another note',
    'create_uid': uid,
}
note_id = call(url, "object", "execute", DB, uid, PASS, 'note.note', 'create', args)
# print("Created new note with data: %s" % print(json.dumps(note_id, indent=2)))
print("Created new note with ID %d" % note_id)
