# SmedgeRender.py
#
# Smedge integration with Blender
#
# Smedge
# Copyright Uberware. All Rights Reserved

"""Simple Smedge submit interface for Blender.

It will use the Smedge Python API, which expects the Smedge "python" folder to be in your PYTHONPATH environment.

To integrate with the Blender menus, create a "smedge_api.py" file in the "startup" scripts folder for Blender:
    import sys
    sys.path.append("/Applications/Smedge.app/Contents/MacOS/python")
    from smedge.dcc import blender
    blender.register()
"""

from pathlib import Path

import bpy
import smedge


class SmedgeRenderOperator(bpy.types.Operator):
    """Submit a render to Smedge."""

    bl_idname = "render.smedge"
    bl_label = "Render in Smedge"

    def execute(self, context):
        """When executed, saves the scene and sends the job to Smedge with the current scene frame range."""
        self.report({'INFO'}, "Sending scene to Smedge")
        scene_path = bpy.data.filepath
        if not scene_path:
            self.report({'ERROR'}, "You must save the scene to disk to render it")
        else:
            bpy.ops.wm.save_mainfile()
            scene_path = Path(scene_path)
            job = {
                "type": "Blender",
                "name": scene_path.stem,
                "scene": scene_path,
                "range": f"{context.scene.frame_start}-{context.scene.frame_end}",
            }
            try:
                result = smedge.submit_jobs(job)
                self.report({'INFO'}, f"Submitted job: {result[0]}")
            except Exception as e:
                self.report({'ERROR'}, str(e))

        return {'FINISHED'}


def menu_func(self, context):
    """Menu function to run the SmedgeRenderOperator."""
    self.layout.operator(SmedgeRenderOperator.bl_idname)


def register():
    """Register the Smedge render command in the menu."""
    bpy.utils.register_class(SmedgeRenderOperator)
    bpy.types.TOPBAR_MT_render.append(menu_func)


def unregister():
    """Remove the Smedge render command from the menu."""
    bpy.utils.unregister_class(SmedgeRenderOperator)
    bpy.types.TOPBAR_MT_render.remove(menu_func)


if __name__ == "__main__":
    register()
