# 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, uuid

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

from ..registries.enum_registry import EnumRegistry
from ..registries.resource_lists_registry import ResourceListsRegistry
from ..awp.utils import section_by_name
from ..utils.dev import log_exception


class ASSET_OT_create_catalog(Operator):
    """
    Create a new (sub)-catalog.
    """
    bl_idname = 'awp.create_catalog'
    bl_label = 'Create'
    bl_description = 'Create new Catalog or Subcatalog'
    bl_options = {'REGISTER'}

    section: StringProperty() # type: ignore

    sub_catalog: BoolProperty(name='Create Subcatalog') # type: ignore

    catalog_back: EnumProperty(
        name='Catalog',
        description='Create Subcatalog',
        items=lambda self, _: [ EnumRegistry.replace_for_enum3(*e) for e in ResourceListsRegistry.get().catalogs(section_by_name(self.section).export_library) ]
    ) # type: ignore

    name: StringProperty(name='Name') # type: ignore

    @property
    def catalog(self, string):
        self.catalog_back = EnumRegistry.id_for_str(string)

    @property
    def catalog(self) -> str:
        return EnumRegistry.str_for_id(self.catalog_back)    
    

    def execute(self, context: bpy.types.Context):
        if self.name:
            try:
                section = section_by_name(self.section)
                fname = sname = self.name
                if self.sub_catalog:
                    entry = ResourceListsRegistry.get().catalog_info(section.export_library, self.catalog)
                    if entry:
                        fname = f'{entry[1]}/{self.name}'
                        sname = f'{entry[2]}-{self.name}'

                id = str(uuid.uuid4())
                if ResourceListsRegistry.get().add_catalog(section.export_library, id, fname, sname):
                    try:
                        section.catalog = id
                    except Exception as e:
                        log_exception(e, context_msg=f'Failed to set catalog ID: {id}')
                    self.report({'INFO'}, 'Catalog created')
                else:
                    self.report({'ERROR'}, 'Catalog already exists')
            except Exception as ex:
                self.report({'ERROR'}, 'Catalog creation failed (see Console)')
        else:
            self.report({'ERROR'}, 'Catalog Name empty')
        
        return {'FINISHED'}


    def draw(self, context: bpy.types.Context):
        l = self.layout.column(align=True)
        section = section_by_name(self.section)
        if ResourceListsRegistry.get().catalogs(section.export_library):
            l.prop(self, 'sub_catalog', icon='ASSET_MANAGER', toggle=True)
            if self.sub_catalog:
                l.prop(self, 'catalog_back', text='Parent')
        l.prop(self, 'name')


    def invoke(self, context, event):
        return context.window_manager.invoke_props_dialog(self)


    def create_ui(l: UILayout, section: str):
        op = l.operator(ASSET_OT_create_catalog.bl_idname, icon='ADD', text='') # type: ASSET_OT_create_catalog
        op.section = section
