import bpy
from . import gen_vlayer, fn


class GPEXP_OT_add_layer_to_render(bpy.types.Operator):
    bl_idname = "gp.add_layer_to_render"
    bl_label = "Add Gp Layer as render nodes"
    bl_description = "Create a view_layer for GP > add node > connect to output"
    bl_options = {"REGISTER"}

    @classmethod
    def poll(cls, context):
        return context.object and context.object.type == 'GPENCIL'

    # mode : bpy.props.StringProperty(options={'SKIP_SAVE'})
    node_scene : bpy.props.StringProperty(default='', 
        description='Scene where to add nodes, Abort if not found', options={'SKIP_SAVE'})

    # File output templates
    base_path : bpy.props.StringProperty(name='Base Path', default='', options={'SKIP_SAVE'})
    file_slot : bpy.props.StringProperty(name='File Slot', default='', options={'SKIP_SAVE'})
    layer_slot : bpy.props.StringProperty(name='Layer Slot', default='', options={'SKIP_SAVE'})

    def execute(self, context):
        ret = gen_vlayer.add_layer_to_render(context.object, node_scene=self.node_scene,
                                             base_path=self.base_path, file_slot=self.file_slot, layer_slot=self.layer_slot)
        if isinstance(ret, tuple):
            self.report({ret[0]}, ret[1])
            if ret[0] == 'ERROR':
                return {'CANCELLED'}
        return {"FINISHED"}

## send operator with mode ALL or SELECTED to batch build
class GPEXP_OT_add_objects_to_render(bpy.types.Operator):
    bl_idname = "gp.add_object_to_render"
    bl_label = "Add all Gp Layer of active object as render nodes"
    bl_description = "Setup GP object in render scene\
                    \nNote: 'send all' mode skip hidden objects"
    bl_options = {"REGISTER"}

    @classmethod
    def poll(cls, context):
        return context.object and context.object.type == 'GPENCIL'

    mode : bpy.props.EnumProperty(
        items=(
            ('ALL', 'All', 'All objects'),
            ('SELECTED', 'Selected', 'Selected objects'),
            ),
            default='ALL', options={'SKIP_SAVE'},
            description='Choice to send all or only selected objects')

    scene : bpy.props.StringProperty(default='', 
        description='Scene where to link object and create viewlayer (create if not exists)', options={'SKIP_SAVE'})
    
    node_scene : bpy.props.StringProperty(default='', 
        description='Scene where to add nodes, Abort if not found', options={'SKIP_SAVE'})

    # File output templates
    base_path : bpy.props.StringProperty(name='Base Path', default='', options={'SKIP_SAVE'})
    file_slot : bpy.props.StringProperty(name='File Slot', default='', options={'SKIP_SAVE'})
    layer_slot : bpy.props.StringProperty(name='Layer Slot', default='', options={'SKIP_SAVE'})

    def execute(self, context):
        ret = gen_vlayer.add_object_to_render(mode=self.mode, scene=self.scene, node_scene=self.node_scene,
                                              base_path=self.base_path, file_slot=self.file_slot, layer_slot=self.layer_slot)
        if isinstance(ret, tuple):
            self.report({ret[0]}, ret[1])
            if ret[0] == 'ERROR':
                return {'CANCELLED'}
        return {"FINISHED"}

class GPEXP_OT_split_to_scene(bpy.types.Operator):
    bl_idname = "gp.split_to_scene"
    bl_label = "Split Objects To Scene"
    bl_description = "Take selected objects and send them to separate scene\n(new scene is named after active object)"
    bl_options = {"REGISTER"}

    @classmethod
    def poll(cls, context):
        return context.object and context.object.type == 'GPENCIL'

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

    def execute(self, context):
        if self.mode == 'ALL':
            print('split selected object in separated scene')
            err = fn.split_object_to_scene()
            if err:
                self.report({'ERROR'}, err)
                return {"CANCELLED"}

        elif self.mode == 'INDIVIDUAL':
            print('split selected object individually in separated scenes')
            errors = []
            selected_objs = [o for o in context.selected_objects]
            scn = context.scene
            for o in reversed(selected_objs):
                err = fn.split_object_to_scene(objs=[o], scene_name=o.name)
                if err:
                    errors.append(err)
                
                ## Reset to current scene (function use ops and go to new scene)
                context.window.scene = scn

            if errors:
                fn.show_message_box(errors, 'Error Log')
                return {"CANCELLED"}

        return {"FINISHED"}

classes=(
GPEXP_OT_add_layer_to_render,
GPEXP_OT_add_objects_to_render,
GPEXP_OT_split_to_scene,
)

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

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