# smedgeRender_C4D.py
# Smedge Submitter Script for Cinema 4D
#
# Smedge
# Copyright Uberware. All Rights Reserved.


#  Initialize
import os

import c4d
import smedge
from c4d import documents, storage, gui

#  Get the document info
fps = doc.GetFps()
scene_name = doc.GetDocumentName()
scene_path = doc.GetDocumentPath()
render_data = doc.GetActiveRenderData()
start_frame = render_data[c4d.RDATA_FRAMEFROM].GetFrame(fps)
end_frame = render_data[c4d.RDATA_FRAMETO].GetFrame(fps)


def padding_and_ext(render_data):
    name_format = render_data[c4d.RDATA_NAMEFORMAT]
    ext = {
        c4d.FILTER_TIF: ".tif",
        c4d.FILTER_TGA: ".tga",
        c4d.FILTER_BMP: ".bmp",
        c4d.FILTER_PICT: ".pict",
        c4d.FILTER_JPG: ".jpg",
        c4d.FILTER_RLA: ".rla",
        c4d.FILTER_RPF: ".rpf",
        c4d.FILTER_B3D: ".b3d",
        c4d.FILTER_TIF_B3D: ".tif",
        c4d.FILTER_PSB: ".psb",
        c4d.FILTER_HDR: ".hdr",
        c4d.FILTER_PNG: ".png",
        c4d.FILTER_IES: ".ies",
    }.get(render_data[c4d.RDATA_FORMAT], "")
    
    if name_format == c4d.RDATA_NAMEFORMAT_0:
        return "%04d" + ext
    elif name_format == c4d.RDATA_NAMEFORMAT_1:
        return "%04d"
    elif name_format == c4d.RDATA_NAMEFORMAT_2:
        return ".%04d"
    elif name_format == c4d.RDATA_NAMEFORMAT_3:
        return "%03d" + ext
    elif name_format == c4d.RDATA_NAMEFORMAT_4:
        return "%03d"
    elif name_format == c4d.RDATA_NAMEFORMAT_5:
        return ".%03d"
    elif name_format == c4d.RDATA_NAMEFORMAT_6:
        return ".%04d" + ext
    else:
        return ""

output_path = render_data[c4d.RDATA_PATH] + padding_and_ext(render_data)

#  Get the whole filename by combining scene path and scene name
full_path = os.path.join(scene_path, scene_name)

job = {
    "Name": f"Render {scene_name}",
    "Type": "Cinema 4D",
    "Scene": full_path,
    "Range": f"{start_frame}-{end_frame}",
}

#  Time to do it!
try:
    result_ids = smedge.submit_jobs(job)
    ids = "\n".join(str(job_id) for job_id in result_ids)
    gui.MessageDialog(f"Submitted to Smedge:\n{ids}")
except Exception as e:
    gui.MessageDialog(f"Submission failed:\n{e}")
