bl_info = {
    "name": "File Browser View",
    "author": "AI",
    "version": (1, 0),
    "blender": (3, 0, 0),
    "location": "File Browser > View",
    "description": "Adds buttons to switch the file browser to different views and control thumbnail size.",
    "category": "File Browser",
}

import bpy
from bpy.props import IntProperty

addon_keymaps = []

# Define preset sizes for thumbnails
THUMBNAIL_SIZES = [64, 96, 128, 192, 256]

def set_file_browser_view(view_type):
    for window in bpy.context.window_manager.windows:
        screen = window.screen
        for area in screen.areas:
            if area.type == 'FILE_BROWSER':
                with bpy.context.temp_override(window=window, area=area):
                    space_data = area.spaces.active
                    params = space_data.params
                    if params:
                        params.display_type = view_type

def get_params(context):
    """Get file browser parameters"""
    space = context.space_data
    if hasattr(space, "params"):
        return space.params
    for area in context.screen.areas:
        if area.type == 'FILE_BROWSER':
            for space in area.spaces:
                if space.type == 'FILE_BROWSER':
                    return space.params
    return None

def get_current_size_index(context):
    """Get the index of the current thumbnail size"""
    params = get_params(context)
    if not params:
        return 2  # Default to middle size
    
    current_size = params.display_size
    return min(range(len(THUMBNAIL_SIZES)), key=lambda i: abs(THUMBNAIL_SIZES[i] - current_size))

class FILEBROWSER_OT_set_thumbnails(bpy.types.Operator):
    """Set File Browser to Thumbnails View"""
    bl_idname = "filebrowser.set_thumbnails"
    bl_label = "Thumbnails"
    bl_options = {'REGISTER', 'UNDO'}
    
    def execute(self, context):
        set_file_browser_view('THUMBNAIL')
        return {'FINISHED'}

class FILEBROWSER_OT_set_vertical_list(bpy.types.Operator):
    """Set File Browser to Vertical List View"""
    bl_idname = "filebrowser.set_vertical_list"
    bl_label = "Vertical List"
    bl_options = {'REGISTER', 'UNDO'}
    
    def execute(self, context):
        set_file_browser_view('LIST_VERTICAL')
        return {'FINISHED'}

class FILEBROWSER_OT_set_horizontal_list(bpy.types.Operator):
    """Set File Browser to Horizontal List View"""
    bl_idname = "filebrowser.set_horizontal_list"
    bl_label = "Horizontal List"
    bl_options = {'REGISTER', 'UNDO'}
    
    def execute(self, context):
        set_file_browser_view('LIST_HORIZONTAL')
        return {'FINISHED'}

class FILEBROWSER_OT_thumbnail_size_change(bpy.types.Operator):
    """Change Thumbnail Size"""
    bl_idname = "file.thumbnail_size_change"
    bl_label = "Change Thumbnail Size"
    bl_description = "Increase or decrease thumbnail size"
    bl_options = {'INTERNAL'}

    increase: bpy.props.BoolProperty(
        name="Increase",
        description="Increase size if True, decrease if False",
        default=True
    )

    def execute(self, context):
        params = get_params(context)
        if not params or params.display_type != 'THUMBNAIL':
            self.report({'WARNING'}, "Only works in thumbnail view mode")
            return {'CANCELLED'}

        current_index = get_current_size_index(context)
        if self.increase:
            new_index = min(current_index + 1, len(THUMBNAIL_SIZES) - 1)
        else:
            new_index = max(current_index - 1, 0)

        params.display_size = THUMBNAIL_SIZES[new_index]

        # Force redraw
        for area in context.screen.areas:
            if area.type == 'FILE_BROWSER':
                area.tag_redraw()

        return {'FINISHED'}

class FILEBROWSER_PT_custom_panel(bpy.types.Panel):
    """Creates a custom panel in the File Browser"""
    bl_label = "Custom File Browser"
    bl_idname = "FILEBROWSER_PT_custom_panel"
    bl_space_type = 'FILE_BROWSER'
    bl_region_type = 'TOOLS'
    bl_category = "View"
    
    def draw(self, context):
        layout = self.layout
        layout.operator("filebrowser.set_thumbnails", icon='FILE_IMAGE')

        # Thumbnail size controls
        row = layout.row(align=True)
        row.operator("file.thumbnail_size_change", text="Increase Size").increase = True
        row.operator("file.thumbnail_size_change", text="Decrease Size").increase = False

        layout.operator("filebrowser.set_vertical_list", icon='ALIGN_JUSTIFY')
        layout.operator("filebrowser.set_horizontal_list", icon='ALIGN_CENTER')


def register():
    bpy.utils.register_class(FILEBROWSER_OT_set_thumbnails)
    bpy.utils.register_class(FILEBROWSER_OT_set_vertical_list)
    bpy.utils.register_class(FILEBROWSER_OT_set_horizontal_list)
    bpy.utils.register_class(FILEBROWSER_OT_thumbnail_size_change)
    bpy.utils.register_class(FILEBROWSER_PT_custom_panel)
    
    wm = bpy.context.window_manager
    if wm.keyconfigs.addon:
        km = wm.keyconfigs.addon.keymaps.new(name="File Browser", space_type='FILE_BROWSER')

# View Mode Shortcuts (CMD + Numpad 1, 2, 3)
        kmi1 = km.keymap_items.new("filebrowser.set_thumbnails", 'NUMPAD_1', 'PRESS', oskey=True)
        addon_keymaps.append((km, kmi1))
        kmi2 = km.keymap_items.new("filebrowser.set_vertical_list", 'NUMPAD_2', 'PRESS', oskey=True)
        addon_keymaps.append((km, kmi2))
        kmi3 = km.keymap_items.new("filebrowser.set_horizontal_list", 'NUMPAD_3', 'PRESS', oskey=True)
        addon_keymaps.append((km, kmi3))

        # Thumbnail Size Shortcuts (CMD + Numpad +, CMD + Numpad -)
        kmi4 = km.keymap_items.new("file.thumbnail_size_change", 'NUMPAD_PLUS', 'PRESS', oskey=True)
        kmi4.properties.increase = True
        addon_keymaps.append((km, kmi4))

        kmi5 = km.keymap_items.new("file.thumbnail_size_change", 'NUMPAD_MINUS', 'PRESS', oskey=True)
        kmi5.properties.increase = False
        addon_keymaps.append((km, kmi5))

        kmi6 = km.keymap_items.new("file.thumbnail_size_change", 'WHEELUPMOUSE', 'PRESS', oskey=True)
        kmi6.properties.increase = True
        addon_keymaps.append((km, kmi6))

        kmi7 = km.keymap_items.new("file.thumbnail_size_change", 'WHEELDOWNMOUSE', 'PRESS', oskey=True)
        kmi7.properties.increase = False
        addon_keymaps.append((km, kmi7))

def unregister():
    bpy.utils.unregister_class(FILEBROWSER_PT_custom_panel)
    bpy.utils.unregister_class(FILEBROWSER_OT_set_thumbnails)
    bpy.utils.unregister_class(FILEBROWSER_OT_set_vertical_list)
    bpy.utils.unregister_class(FILEBROWSER_OT_set_horizontal_list)
    bpy.utils.unregister_class(FILEBROWSER_OT_thumbnail_size_change)
    
    wm = bpy.context.window_manager
    if wm.keyconfigs.addon:
        for km, kmi in addon_keymaps:
            km.keymap_items.remove(kmi)
        addon_keymaps.clear()

if __name__ == "__main__":
    register()
