import bpy
from . import fn
from .constant import RD_SCENE_NAME

class GPEXP_OT_clear_render_tree(bpy.types.Operator):
    bl_idname = "gp.clear_render_tree"
    bl_label = "Clear Render Node Tree "
    bl_description = "Clear node tree from render scene"
    bl_options = {"REGISTER"}

    @classmethod
    def poll(cls, context):
        return True

    mode : bpy.props.StringProperty(default='NORMAL', options={'SKIP_SAVE'})

    def execute(self, context):

        render = fn.get_render_scene(create=False)
        if not render:
            print(f'SKIP, no {RD_SCENE_NAME} scene')
            return {"CANCELLED"}

        scn = context.scene

        # Clear all nodes in frames
        if scn.use_nodes:
            for i in range(len(scn.node_tree.nodes))[::-1]:

                # Skip frames to delete later
                if scn.node_tree.nodes[i].type == 'FRAME':
                    continue

                # Skip unparented nodes
                if not scn.node_tree.nodes[i].parent:
                    continue
                scn.node_tree.nodes.remove(scn.node_tree.nodes[i])

        # Delete all frames
        if scn.use_nodes:
            for i in range(len(scn.node_tree.nodes))[::-1]:
                if scn.node_tree.nodes[i].type == 'FRAME':
                    scn.node_tree.nodes.remove(scn.node_tree.nodes[i])

        # Clear all "NG_" nodegroups
        for ng in reversed(bpy.data.node_groups):
            if ng.name.startswith('NG_'):
                ng.use_fake_user = False
                bpy.data.node_groups.remove(ng)


        if self.mode == 'COMPLETE':
            bpy.data.scenes.remove(render)
            return {"FINISHED"}

        # Clear all view_layers
        for vl in reversed(render.view_layers):
            if ' / ' in vl.name:
                render.view_layers.remove(vl)

        return {"FINISHED"}

classes=(
GPEXP_OT_clear_render_tree,
)

def register():
    for cls in classes:
        bpy.utils.register_class(cls)

def unregister():
    for cls in reversed(classes):
        bpy.utils.unregister_class(cls)