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

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

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

class ASSET_OT_create_new_blend(Operator):
    """
    Create an empty new blend file (if not exists).
    """
    bl_idname = 'awp.create_new_blend'
    bl_label = ''
    bl_description = ''
    bl_options = {'REGISTER'}


    path: StringProperty() # type: ignore
    file: StringProperty(name='File Name', description='Name of new File (without .blend)') # type: ignore
    section: StringProperty() # type: ignore


    @classmethod
    def description(cls, context, properties):
        return f'Create a new, empty Asset Library .blend File in "{properties.path}"'


    def execute(self, context: bpy.types.Context):
        filename = os.path.join(
            self.path, 
            self.file if self.file.endswith('.blend') else f'{self.file}.blend'
        )
        if not os.path.exists(filename):
            try:
                # Create file.
                bpy.data.libraries.write(filename, set(), compress=True)

                # Update local lists.
                ResourceListsRegistry.get().update(False)

                # Set as default.
                fixed_name = os.path.splitext(self.file)[0]
                section = section_by_name(self.section)
                for e in ResourceListsRegistry.get().library_files(section.export_library):
                    if e[1] == fixed_name:
                        try:
                            section.export_file = e[0]
                        except Exception as e:
                            # Not an error.
                            #log_exception(e, operator=self, context_msg=f'Failed to set export file for section: {section.name}')
                            pass
                        break
            except Exception as e:
                log_exception(e, operator=self, context_msg='Failed to create new blend file')
        else:
            self.report({'ERROR'}, 'File already exists')

        return {'FINISHED'}


    def draw(self, context: bpy.types.Context):
        l = self.layout.column(align=True)
        l.label(text=self.path)
        l.prop(self, 'file')


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


    @staticmethod
    def create_ui(l: UILayout, path: str, section: str, as_icon: bool = False):
        op = l.operator(ASSET_OT_create_new_blend.bl_idname, icon='ADD', text='' if as_icon else 'New File') # type: ASSET_OT_create_new_blend
        op.path = path
        op.section = section
