import adsk.core, adsk.fusion, adsk.cam, traceback
import os
import uuid

app = None
ui = None
handlers = []

def onExecuteSaveAs(args):
    try:
        doc = app.activeDocument
        design = app.activeProduct
        
        if not hasattr(design, 'exportManager'):
            ui.messageBox("Current document cannot be exported.")
            return
            
        export_mgr = design.exportManager
        
        # Show file save dialog
        file_dialog = ui.createFileDialog()
        file_dialog.title = "Export As"
        file_dialog.filter = "Fusion 360 Files (*.f3d)"
        
        if doc.dataFile:
            initial_dir = os.path.dirname(doc.dataFile.name)
            file_dialog.initialDirectory = initial_dir

        if file_dialog.showSave() != adsk.core.DialogResults.DialogOK:
            return

        file_path = file_dialog.filename
        file_ext = os.path.splitext(file_path)[1].lower()

        # Verify file extension
        if file_ext not in ['.f3d']:
            ui.messageBox("Invalid file type. Please export as .f3d")
            return

        # Create appropriate export options based on file extension
        options = export_mgr.createFusionArchiveExportOptions(file_path)
        
        export_mgr.execute(options)
            
        ui.messageBox(f"File exported to: {file_path}")
    except Exception as e:
        if ui:
            ui.messageBox(f"Failed to export file: {e}")

class SaveCommandCreatedHandler(adsk.core.CommandCreatedEventHandler):
    def __init__(self, execute_function):
        super().__init__()
        self.execute_function = execute_function

    def notify(self, args):
        try:
            command = args.command
            on_execute_handler = SaveCommandExecuteHandler(self.execute_function)
            command.execute.add(on_execute_handler)
            handlers.append(on_execute_handler)
        except Exception as e:
            if ui:
                ui.messageBox(f"Failed to create command: {e}")

class SaveCommandExecuteHandler(adsk.core.CommandEventHandler):
    def __init__(self, execute_function):
        super().__init__()
        self.execute_function = execute_function

    def notify(self, args):
        try:
            self.execute_function(args)
        except Exception as e:
            if ui:
                ui.messageBox(f"Failed to execute command: {e}")

def run(context):
    global app, ui
    app = adsk.core.Application.get()
    ui = app.userInterface

    try:
        tab_id = f'LocalSaveTab_{uuid.uuid4()}'
        panel_id = f'LocalSavePanel_{uuid.uuid4()}'
        save_as_command_id = f"SaveAsLocalCommand_{uuid.uuid4()}"

        current_dir = os.path.dirname(os.path.abspath(__file__))
        save_as_icon_path = os.path.join(current_dir, 'resources', '32x32-saveas.png')
        panel_icon_path = os.path.join(current_dir, 'resources', '32x32-panel.png')

        workspace = ui.workspaces.itemById('FusionSolidEnvironment')
        
        for tab in workspace.toolbarTabs:
            if tab.id.startswith('LocalSaveTab'):
                tab.deleteMe()
                break

        tab = workspace.toolbarTabs.add(tab_id, 'Local Save')
        panel = tab.toolbarPanels.add(panel_id, 'Save Options', panel_icon_path)

        try:
            save_as_command_def = ui.commandDefinitions.addButtonDefinition(
                save_as_command_id, 
                'Save', 
                'Save the file locally. Use this for initial save and override of file.', 
                save_as_icon_path
            )

            save_as_created_handler = SaveCommandCreatedHandler(onExecuteSaveAs)
            save_as_command_def.commandCreated.add(save_as_created_handler)

            handlers.append(save_as_created_handler)

            panel.controls.addCommand(save_as_command_def)
                
        except Exception as e:
            ui.messageBox(f"Error creating commands: {e}")
            return

    except Exception as e:
        if ui:
            ui.messageBox(f"Failed to run the plugin: {e}")

def stop(context):
    try:
        workspace = ui.workspaces.itemById('FusionSolidEnvironment')
        if workspace:
            tab = workspace.toolbarTabs.itemById('LocalSaveTab')
            if tab:
                tab.deleteMe()

        command_definitions_to_delete = []
        for cmd_def in ui.commandDefinitions:
            if cmd_def.id.startswith('SaveAsLocalCommand_'):
                command_definitions_to_delete.append(cmd_def)

        for cmd_def in command_definitions_to_delete:
            cmd_def.deleteMe()

    except Exception as e:
        if ui:
            ui.messageBox(f"Failed to stop the plugin: {e}")