# Copyright (C) 2022 Thomas Hoppe (h0bB1T). All rights reserved.
#
# Unauthorized copying of this file via any medium is strictly prohibited.
# Proprietary and confidential.

import bpy, sys, json

from typing import Dict

# No package imports here!


class PreviewRenderer:
    def __init__(self, dct: Dict[str, str], preview: str, size: int):
        self.dct = dct
        self.preview = preview
        self.size = size
        
        
    def add_tex(self, tree: bpy.types.ShaderNodeTree, type: str, cs: str):
        if type in self.dct and self.dct[type]:
            tex = tree.nodes.new('ShaderNodeTexImage')
            im = bpy.data.images.load(self.dct[type])
            im.colorspace_settings.name = cs
            tex.image = im
            return tex
        return None


    def setup_material(self, tree: bpy.types.ShaderNodeTree):
        tree.nodes.clear()

        out = tree.nodes.new('ShaderNodeOutputMaterial')
        shd = tree.nodes.new('ShaderNodeEmission')
        tree.links.new(shd.outputs[0], out.inputs[0])
        
        img = self.add_tex(tree, 'image', 'Non-Color')
        tree.links.new(img.outputs[0], shd.inputs[0])


    def run(self):
        self.setup_material(bpy.data.materials['Preview'].node_tree)

        bpy.context.scene.render.resolution_x = self.size
        bpy.context.scene.render.resolution_y = self.size
        bpy.context.scene.render.engine = 'CYCLES'
        bpy.context.scene.render.filepath = self.preview
        bpy.context.scene.render.image_settings.file_format = 'JPEG'
        bpy.ops.render.render(write_still=True)



def main(args):
    print("Script args: ", args)
    js, preview, size = args
    PreviewRenderer(json.loads(js), preview, int(size)).run()


if __name__ == "__main__":
    if "--" not in sys.argv:
        argv = []  # as if no args are passed
    else:
        argv = sys.argv[sys.argv.index("--") + 1:]  # get all args after "--"
    main(argv)
