import bpy
from .utils_debug import debug_log
from .utils_web_project import openInBrowser

from .utils import deleteDirectoryRecursive, openFile, showMessage

class NEEDLE_OT_OpenPreferences(bpy.types.Operator):
    bl_idname = "needle.open_preferences"
    bl_label = "Open Preferences"
    bl_description = "Opens the preferences for this addon"

    showMessage: bpy.props.StringProperty()
    
    def execute(self, _context):
        openAddonPreferences(_context)
        return {'FINISHED'}
    
def openAddonPreferences(context):
    bpy.ops.screen.userpref_show('INVOKE_DEFAULT')
    bpy.context.preferences.active_section = 'ADDONS'
    bpy.data.window_managers["WinMan"].addon_search = "needle"
    bpy.ops.preferences.addon_expand(module=__package__)
    bpy.ops.preferences.addon_show(module=__package__)

class NEEDLE_OT_OpenChangelog(bpy.types.Operator):
    bl_idname = "needle.open_changelog"
    bl_label = "Open Changelog"
    bl_description = "Opens the changelog for this addon"
    
    def execute(self, context):
        import os
        addonDirectory = os.path.dirname(os.path.abspath(__file__))
        changelogPath = addonDirectory + "/CHANGELOG.md"
        showMessage(changelogPath, "Opening Changelog")
        # TODO: test if this works on OSX or Linux
        openFile(changelogPath)
        return {'FINISHED'}
    
class NEEDLE_OT_OpenURL(bpy.types.Operator):
    bl_idname = "needle.open_url"
    bl_label = "Open Url"
    bl_description = "Open a url in the default browser"
    url: bpy.props.StringProperty()
    def execute(self, context):
        openInBrowser(self.url)
        return {'FINISHED'}



class NEEDLE_OT_ShowLogs(bpy.types.Operator):
    bl_idname = "needle.open_log"
    bl_label = "Open Needle Log"
    bl_description = ""
    open_logs_directory: bpy.props.BoolProperty(default=False)
    def execute(self, context):
        if self.open_logs_directory:
            from .utils_debug import openLogDirectory
            openLogDirectory()
        else:
            from .utils_debug import openLogFile
            openLogFile()
        return {'FINISHED'}



class NEEDLE_OT_ShowMessageBox(bpy.types.Operator):
    bl_idname = "needle.show_message_box"
    bl_label = "Message box"
    bl_description = ""

    message: bpy.props.StringProperty()

    def execute(self, context):
        showMessage(self.message)
        return {'FINISHED'}


class NEEDLE_OT_SelectFile(bpy.types.Operator):
    bl_idname = "needle.select_file"
    bl_label = "Select a file"
    bl_options = {'REGISTER'}
    bl_description = "The selected file will be loaded into your blender file - currently supporting Video (mp4), Audio (mp3) and Image (jpg, png)."
    
    filter_glob: bpy.props.StringProperty(default = '*',options = {'HIDDEN'})
    filepath: bpy.props.StringProperty(subtype="FILE_PATH")


    def execute(self, context):
        path = self.filepath
        print("Selected file: '" + path + "'")
        # if current blend file is saved
        if bpy.data.filepath:
            relpath = bpy.path.relpath(path)
            print("Current blend file is saved → using relative path: " + relpath)
            path = relpath;
        try:
            if path.endswith(".mp4") or path.endswith(".ogg"):
                for clip in bpy.data.movieclips:
                    if clip.filepath == path:
                        showMessage("Video already loaded: " + path, "Video")
                        return {'FINISHED'}
                bpy.data.movieclips.load(path)
                showMessage("Loaded Video: " + path, "Video")
            
            elif path.endswith(".mp3") or path.endswith(".wav"):
                for clip in bpy.data.sounds:
                    if clip.filepath == path:
                        showMessage("Audio already loaded: " + path, "Audio")
                        return {'FINISHED'}
                bpy.data.sounds.load(path)
                showMessage("Loaded Audio: " + path, "Audio")
                if path.endswith(".wav"):
                    showMessage("Loading WAV files for use in web is not recommended. Consider converting your file to mp3", "Audio")

            elif path.endswith(".jpg") or path.endswith(".png") or path.endswith(".jpeg") or path.endswith(".webp"):
                for img in bpy.data.images:
                    if img.filepath == path:
                        showMessage("Image already loaded: " + path, "Image")
                        return {'FINISHED'}
                bpy.data.images.load(path)
                showMessage("Loaded Image: " + path, "Image")
            else:
                debug_log("Unsupported file type: " + path)
                showMessage("Unsupported file type: " + path, "Unsupported")
        finally:
            pass
        return {'FINISHED'}

    # We want a file
    def invoke(self, context, event):
        # https://docs.blender.org/api/current/bpy.types.WindowManager.html#bpy.types.WindowManager.fileselect_add
        context.window_manager.fileselect_add(self)
        return {'RUNNING_MODAL'}

class NEEDLE_OT_SelectDirectory(bpy.types.Operator):
    bl_idname = "needle.select_dir"
    bl_label = "Select a directory"
    bl_options = {'REGISTER'}

    # We want a directory
    directory = bpy.props.StringProperty(
        name="Path",
        description="Select a directory"
        )
    # only show folders
    filter_folder = bpy.props.BoolProperty(default=True, options={'HIDDEN'})

    def execute(self, context):
        print("Selected dir: '" + self.directory + "'")
        return {'FINISHED'}

    def invoke(self, context, event):
        # https://docs.blender.org/api/current/bpy.types.WindowManager.html#bpy.types.WindowManager.fileselect_add
        context.window_manager.fileselect_add(self)
        return {'RUNNING_MODAL'}



class NEEDLE_OT_DeleteDirectory(bpy.types.Operator):
    bl_idname = "needle.delete_dir"
    bl_label = "Delete a directory including subfolders"
    bl_options = {'REGISTER'}

    # We want a directory
    directory: bpy.props.StringProperty(
        name="Path",
        description="Directory to delete"
        )

    # recursive: bpy.props.BoolProperty(name="Recursive", default=True)
        

    def execute(self, context):
        deleteDirectoryRecursive(self.directory)
        return {'FINISHED'}