"""
Util function for this addon
"""

import bpy
from . bl_utils import get_addon_prefs


def thumbnail_blend_file(input_blend, output_img):
    input_blend = Path(input_blend).resolve()
    output_img = Path(output_img).resolve()

    print(f'Thumbnailing {input_blend} to {output_img}')
    blender_thumbnailer = Path(bpy.app.binary_path).parent / 'blender-thumbnailer'

    output_img.parent.mkdir(exist_ok=True, parents=True)

    subprocess.call([blender_thumbnailer, str(input_blend), str(output_img)])

    success = output_img.exists()

    if not success:
        empty_preview = RESOURCES_DIR / 'empty_preview.png'
        shutil.copy(str(empty_preview), str(output_img))

    return success


def get_active_library():
    '''Get the pref library properties from the active library of the asset browser'''
    prefs = get_addon_prefs()
    lib_ref = bpy.context.space_data.params.asset_library_reference

    #Check for merged library
    for l in prefs.libraries:
        if l.name == lib_ref:
            return l


def update_library_path(self, context):
    """Removing all asset libraries and recreate them"""

    addon_prefs = get_addon_prefs()
    libs = context.preferences.filepaths.asset_libraries

    for i, lib in reversed(list(enumerate(libs))):
        if (addon_lib := addon_prefs.libraries.get(lib.name)) and addon_lib.path == lib.path:
            bpy.ops.preferences.asset_library_remove(index=i)

    for addon_lib in addon_prefs.libraries:
        if not addon_lib.use:
            continue
        bpy.ops.preferences.asset_library_add(directory=str(addon_lib.path))
        libs[-1].name = addon_lib.name