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

from typing import List
import bpy, traceback

from bpy.types import Operator, UILayout
from bpy.props import StringProperty

from ..utils.blender import DropNodeOperator
from ..registries.asset_registry import AssetEntry


class ASSET_OT_import_node(Operator, DropNodeOperator):
    """
    Import node.
    """
    bl_idname = 'awp.import_node'
    bl_label = ''
    bl_description = ''
    bl_options = {'REGISTER', 'UNDO'}


    mode: StringProperty() # type: ignore
    filename: StringProperty() # type: ignore
    asset: StringProperty() # type: ignore
    desc: StringProperty() # type: ignore


    @classmethod
    def description(cls, context, properties):
        return properties.desc if properties.desc else f'{properties.asset} ({properties.filename})'


    def execute(self, context: bpy.types.Context):
        try:
            # Load the node.
            with bpy.data.libraries.load(self.filename, link=False) as (_, data_to):
                data_to.node_groups = [self.asset]
                nodes = data_to.node_groups # type: List[bpy.types.NodeGroup]
            nodes[0].asset_clear() # Remove asset tag, otherwise a possible reexport may create duplicates in lib.

            # Drop the node.
            tp = 'GeometryNodeGroup' if self.mode == 'GEOMETRY' else 'ShaderNodeGroup'
            bpy.ops.node.add_node(
                type=tp, 
                use_transform=True, 
                settings=[{
                    'name': 'node_tree', 
                    'value': "bpy.data.node_groups['%s']" % nodes[0].name
                }]
            )

            return {'FINISHED'}
        except Exception as ex:
            print(traceback.format_exc())
            self.report({'ERROR'}, f'Asset loading failed, see Console ({ex})')
            return {'FINISHED'}


    @staticmethod
    def create_ui(l: UILayout, mode: str, asset: AssetEntry):
        op = l.operator(ASSET_OT_import_node.bl_idname, text=asset.name, icon='NODE') # type: ASSET_OT_import_node
        op.mode = mode
        op.filename = asset.blend
        op.asset = asset.name
        op.desc = asset.description
        