# cython: language_level=3
import copy
import logging
import os
import platform
import tempfile
import sys
from collections import namedtuple
from numbers import Number
from tempfile import TemporaryDirectory

import numpy as np
import OpenGL.GL as gl
from cython cimport view
from cython.parallel import parallel, prange
from libc.stdlib cimport malloc, free
from libc.string cimport strncpy
from pymj import const
import os

include "generated/wrappers.pxi"
include "opengl_context.pyx"
include "mjsim.pyx"
include "mjsimpool.pyx"
include "mjsimstate.pyx"
include "mjrendercontext.pyx"

cdef extern from "gl/glshim.h":

    cdef int initOpenGL(int device_id)
    cdef void closeOpenGL()
    cdef int setOpenGLBufferSize(int width, int height)

# TODO: make this function or class so these comments turn into doc strings:

# Python warning callback function, which is set
# MuJoCo has a user-settable callback function for warnings: mju_user_warning()
# We want to supply a python function, and be able to raise exceptions.
# To do this we have to wrap two things:

# This is the python callback function.  We save it in the global() context
# so we can access it from a C wrapper function (c_warning_callback)
cdef object py_warning_callback
# This is the saved exception.  Because the C callback can not propagate
# exceptions, this must be set to None before calling into MuJoCo, and then
# inspected afterwards.
# These are combined in a simple class which handles both:
#   with wrap_mujoco_warning():
#       mj_somefunc()
cdef object py_warning_exception = None


cdef void c_warning_callback(const char *msg) with gil:
    '''
    Wraps the warning callback so we can raise exceptions.
    Because callbacks can't propagate exceptions, we set a global that has
        to be inspected later.
    Use wrap_mujoco_warning() to check for that saved exception and
        re-raise it back to the caller.
    '''
    global py_warning_callback
    try:
        (<object> py_warning_callback)(msg)
    except Exception as e:
        global py_warning_exception
        py_warning_exception = e


def set_warning_callback(warn):
    '''
    Set a user-defined warning callback.  It should take in a string message
        (the warning string) and raise an Exception.
    See c_warning_callback, which is the C wrapper to the user defined function
    '''
    global py_warning_callback
    global mju_user_warning
    py_warning_callback = warn
    mju_user_warning = c_warning_callback


def get_warning_callback():
    '''
    Returns the user-defined warning callback, for use in e.g. a context
    manager.
    '''
    global py_warning_callback
    return py_warning_callback


class wrap_mujoco_warning(object):
    '''
    Class to wrap capturing exceptions raised during warning callbacks.
    Use this to capture warnings in mujoco calls.  Example:
        with wrap_mujoco_warning():
            mj_somefunc()
    '''
    def __enter__(self):
        global py_warning_exception
        py_warning_exception = None
    def __exit__(self, type, value, traceback):
        global py_warning_exception
        if py_warning_exception is not None:
            raise py_warning_exception


def activate(license_path):
    """Activate MuJoCo given a path to a license file."""
    return mj_activate(license_path.encode())

def load_model_from_path(str path):
    """Loads model from path."""
    cdef char errstr[300]
    cdef mjModel *model
    with wrap_mujoco_warning():
        model = mj_loadXML(path.encode(), NULL, errstr, 300)
    if model == NULL:
        raise Exception('Failed to load XML file: %s. mj_loadXML error: %s' % (path, errstr,))
    return WrapMjModel(model)

def load_model_from_xml(str xml_str):
    """
    Loads and returns a PyMjModel model from a string containing XML markup.
    Saves the XML string used to create the returned model in `model.xml`.
    """
    cdef char errstr[300]
    cdef mjModel *model
    with wrap_mujoco_warning():
        with tempfile.NamedTemporaryFile(suffix=".xml", delete=False) as fp:
            fp.write(xml_str.encode())
            fp.flush()
        model = mj_loadXML(fp.name.encode(), NULL, errstr, 300)
    if model == NULL:
        raise Exception('%s\nFailed to load XML from file: %s. mj_loadXML error: %s' % (xml_str, fp.name, errstr,))
    return WrapMjModel(model)


def load_model_from_mjb(bytes mjb_bytes):
    """
    Loads and returns a PyMjModel model from bytes encoded MJB.
    MJB is a MuJoCo-custom format that includes assets like meshes/textures.
    """
    cdef mjModel *model
    with wrap_mujoco_warning():
        with TemporaryDirectory() as td:
            filename = os.path.join(td, 'model.mjb')
            with open(filename, 'wb') as f:
                f.write(mjb_bytes)
            model = mj_loadModel(filename.encode(), NULL)
    if model == NULL:
        raise Exception('%s\nFailed to load MJB')
    return WrapMjModel(model)


