# 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 Dict, List
import bpy

from bpy.types import Panel

from ..registries.asset_registry import AssetEntry
from ..properties import Properties
from ..constants import panel_name
from ..registries.resource_lists_registry import ResourceListsRegistry
from ..utils.blender import is_valid_node_space
from ..utils.tools import local_addon_info
from ..operators.import_node import ASSET_OT_import_node
from ..operators.multi_purpose import ASSET_OT_multi_purpose


class NODE_PT_awp_import_nodes_panel(Panel):
    """
    Shown in both Shader and Geometry side panel, imports 
    and drops nodes from assets.
    """
    bl_label = 'Import'
    bl_idname = 'NODE_PT_awp_import_shader_geometry_panel'
    bl_space_type = 'NODE_EDITOR'
    bl_region_type = 'UI'
    bl_category = panel_name


    @classmethod
    def poll(cls, context):
        return is_valid_node_space(context, ['GeometryNodeTree', 'ShaderNodeTree']) and local_addon_info.vl()


    def draw(self, context: bpy.types.Context):
        is_shader = context.space_data.tree_type == 'ShaderNodeTree'
        c = self.layout.column(align=True)

        props = Properties.get()
        c.prop(props, 'shader_node_filter' if is_shader else 'geometry_node_filter', text='',)

        flt = (props.shader_node_filter if is_shader else props.geometry_node_filter).lower() # type: str
        shaders = ResourceListsRegistry.get().shader_nodes() if is_shader else ResourceListsRegistry.get().geometry_nodes() 

        sections = {} # type: Dict[str, List[AssetEntry]]
        for shader in shaders:
            # Skip if filtered by name.
            if flt and not flt in shader.name.lower():
                continue

            sections.setdefault(shader.tags[0] if shader.tags else 'Other', []).append(shader)

        for section in sorted(sections.keys()):
            c.label(text=f'{section}:')
            for shader in sorted(sections[section], key=lambda x: x.name):
                r = c.row(align=True)
                ASSET_OT_import_node.create_ui(r, 'SHADER' if is_shader else 'GEOMETRY', shader)
                ASSET_OT_multi_purpose.create_ui_open_asset(r, shader.blend)
                