import ctypes
import requests

dll = ctypes.cdll.LoadLibrary("./python_use_dll/owotrender_rs.dll")

dll.render_world.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
dll.render_world.restype = ctypes.c_void_p

dll.free_query.argtypes = [ctypes.c_void_p]
dll.free_query.restype = None

def render_world(world:str="",outpath:str="./render.png"):
    worlddata = requests.get(f"https://ourworldoftext.com/world_props/?world={world.strip('/')}")
    if worlddata.status_code != 404:
        worlddata=worlddata.json()
        protocol = "http://"
        base = "ourworldoftext.com/"
        suffix = "/?fetch=1&min_tileX=-10&min_tileY=-10&max_tileX=9&max_tileY=9&array=1"
        url = f"{base}{world}{suffix}"
        while "//" in url:
            url = url.replace("//","/")
        url = f"{protocol}{url}"
        data = requests.get(
                url
            ).text.encode("utf-8",errors="ignore")
        ptr = dll.render_world(
            data,
            outpath.encode("utf-8"),
            worlddata["writability"],
            int(worlddata["theme"]["color"].strip("#"),16) if worlddata["theme"]["color"] != "" else 0xffffff,
            int(worlddata["theme"]["tileMember"].strip("#"),16) if worlddata["theme"]["tileMember"] != "" else 0xeeeeee,
            int(worlddata["theme"]["tileOwner"].strip("#"),16) if worlddata["theme"]["tileOwner"] != "" else 0xdddddd,
            int(worlddata["theme"]["publicText"].strip("#"),16) if worlddata["theme"]["publicText"] != "" else 0,
            int(worlddata["theme"]["memberText"].strip("#"),16) if worlddata["theme"]["memberText"] != "" else 0,
            int(worlddata["theme"]["ownerText"].strip("#"),16) if worlddata["theme"]["ownerText"] != "" else 0,
        )

        result = ctypes.cast(ptr, ctypes.c_char_p).value.decode()
        dll.free_query(ptr)
        return (result,data)
    protocol = "http://"
    base = "ourworldoftext.com/"
    suffix = "/?fetch=1&min_tileX=-10&min_tileY=-10&max_tileX=9&max_tileY=9&array=1"
    url = f"{base}{world}{suffix}"
    while "//" in url:
        url = url.replace("//","/")
    url = f"{protocol}{url}"
    data = requests.get(
            url
        )
    code = data.status_code
    data = data.text.encode("utf-8",errors="ignore")
    if code == 404:
        return ("World gave 404!",data)
    ptr = dll.render_world(
        data,
        outpath.encode("utf-8"),
        0,
        0xffffff,
        0xeeeeee,
        0xdddddd,
        0,
        0,
        0,
    )

    result = ctypes.cast(ptr, ctypes.c_char_p).value.decode()
    dll.free_query(ptr)
    return (result,data)

print(render_world("/wottt","wottt.png")[0])
print(render_world("/jtpl/warned","warned.png")[0])
print(render_world("/cgi","cgi.png")[0])
print(render_world("/main","main.png")[0])