# SPDX-License-Identifier: GPL-2.0-or-later


from typing import List, Tuple

import bpy
from bpy.app.handlers import persistent

addon_keymaps: List[Tuple[bpy.types.KeyMap, bpy.types.KeyMapItem]] = []


@persistent
def copy_play_anim(dummy):
    wm = bpy.context.window_manager
    km = wm.keyconfigs.addon.keymaps.new(name="File Browser Main", space_type="FILE_BROWSER")

    km_frames = wm.keyconfigs.user.keymaps.get('Frames')
    if km_frames:
        play = km_frames.keymap_items.get('screen.animation_play')
        if play:
            kmi = km.keymap_items.new(
                "assetlib.play_preview", 
                play.type, play.value,
                any=play.any, shift=play.shift, ctrl=play.ctrl, alt=play.alt,
                oskey=play.oskey, key_modifier=play.key_modifier,
                )
            addon_keymaps.append((km, kmi))


def register() -> None:
    wm = bpy.context.window_manager
    if wm.keyconfigs.addon is None:
        # This happens when Blender is running in the background.
        return

    km = wm.keyconfigs.addon.keymaps.new(name="File Browser Main", space_type="FILE_BROWSER")

    kmi = km.keymap_items.new("wm.call_menu", "RIGHTMOUSE", "PRESS")
    kmi.properties.name = 'ASSETLIB_MT_context_menu'
    addon_keymaps.append((km, kmi))

    kmi = km.keymap_items.new("assetlib.play_preview", "SPACE", "PRESS")
    addon_keymaps.append((km, kmi))

    # km = addon.keymaps.new(name = "Grease Pencil Stroke Paint Mode", space_type = "EMPTY")
    # kmi = km.keymap_items.new('wm.call_panel', type='F2', value='PRESS')

    if 'copy_play_anim' not in [hand.__name__ for hand in bpy.app.handlers.load_post]:
        bpy.app.handlers.load_post.append(copy_play_anim)

def unregister() -> None:
    # Clear shortcuts from the keymap.
    if 'copy_play_anim' in [hand.__name__ for hand in bpy.app.handlers.load_post]:
        bpy.app.handlers.load_post.remove(copy_play_anim)
 
    for km, kmi in addon_keymaps:
        km.keymap_items.remove(kmi)
    addon_keymaps.clear()