"""This file acts as the main module for this script."""

import traceback
import adsk.core
import adsk.fusion
import adsk.cam

# Initialize the global variables for the Application and UserInterface objects.
app = adsk.core.Application.get()
ui = app.userInterface

handlers = []

maxCount = 100
defultRectSize = adsk.core.ValueInput.createByReal(5) #5 cm 


def run(_context: str):
    """This function is called by Fusion when the script is run."""

    try:

        # Get the CommandDefinitions collection to replace this command with the current one
        cmdDefs = ui.commandDefinitions
        
        existingDef = cmdDefs.itemById("CreateVelvetGrid")
        if existingDef:
            existingDef.deleteMe()
        # Create a button command definition.
        makeGridButton = cmdDefs.addButtonDefinition(
            "CreateVelvetGrid",
            "Create Velvet Grid Layout",
            "Dynamically make the grid.",
        )
        # Connect to the command created event.
        makeGridCommandCreated = MakeGridCommandCreatedEventHandler()
        makeGridButton.commandCreated.add(makeGridCommandCreated)
        handlers.append(makeGridCommandCreated)
        # Execute the command.
        makeGridButton.execute()

        # Keep the script running.
        adsk.autoTerminate(False)

    except:  # pylint:disable=bare-except
        # Write the error message to the TEXT COMMANDS window.
        app.log(f"Failed:\n{traceback.format_exc()}")


# Event handler for the commandCreated event.
class MakeGridCommandCreatedEventHandler(adsk.core.CommandCreatedEventHandler):
    def __init__(self):
        super().__init__()

    def notify(self, args):
        eventArgs = adsk.core.CommandCreatedEventArgs.cast(args)
        cmd = eventArgs.command
        inputs = cmd.commandInputs

        inputs.addDistanceValueCommandInput(
            "baseThickness",
            "Base Thickness",
            adsk.core.ValueInput.createByReal(1),
        )
        inputs.addDistanceValueCommandInput(
            "deviderHeight",
            "Divider Height",
            adsk.core.ValueInput.createByReal(0.5),
        )
        inputs.addIntegerSpinnerCommandInput("rowCount", "Row Count", 1, maxCount, 1, 3)
        inputs.addIntegerSpinnerCommandInput(
            "columnCount", "Column Count", 1, maxCount, 1, 3
        )

        inputs.addDistanceValueCommandInput(
            "rowheight",
            "Row Height",
            defultRectSize,
        )
        inputs.addDistanceValueCommandInput(
            "columnWidth",
            "Column Width",
            defultRectSize,
        )

        inputs.addDistanceValueCommandInput(
            "innerOffset",
            "Inner Spacing",
            adsk.core.ValueInput.createByReal(0.5),
        )
        inputs.addDistanceValueCommandInput(
            "outerOffset",
            "Outer Spacing",
            adsk.core.ValueInput.createByReal(1),
        )

        #TODO: the table should be visble only if this is on, the custom sizes are optional 
        customSizes = inputs.addBoolValueInput(
            "customSizes", "customSizes", True, "", False
        )

        rowsTable = inputs.addTableCommandInput("rowsTable", "Rows", 2, "1:1")
        columnsTable = inputs.addTableCommandInput("columnsTable", "Columns", 2, "1:1")

        #TODO: make them add rows
        add_button_rows = inputs.addBoolValueInput("rowsTable_AddButton", "➕", False)
        add_button_columns = inputs.addBoolValueInput("columnsTable_AddButton", "➕", False)
        
        rowsTable.addToolbarCommandInput(add_button_rows)
        columnsTable.addToolbarCommandInput(add_button_columns)

        title_index_rows = inputs.addTextBoxCommandInput('rowIndex_col_subTitle', 'row Index', 'Row', 1, True)
        title_size_rows = inputs.addTextBoxCommandInput('rowSize_col_subTitle', 'rows size', 'size', 1, True)
        title_index_columns = inputs.addTextBoxCommandInput('columnIndex_col_subTitle', 'column Index', 'Column', 1, True)
        title_size_columns = inputs.addTextBoxCommandInput('columnSize_col_subTitle', 'column size', 'size', 1, True)

        rowsTable.addCommandInput(title_index_rows, 0, 0,)
        rowsTable.addCommandInput(title_size_rows, 0, 1)
        columnsTable.addCommandInput(title_index_columns, 0, 0)
        columnsTable.addCommandInput(title_size_columns, 0, 1)

        row_number = inputs.addIntegerSpinnerCommandInput(
            "row_number_0", "Row Number", 1, maxCount, 1, 1
        )
        column_number = inputs.addIntegerSpinnerCommandInput(
            "column_number_0", "Column Number", 1, maxCount, 1, 1
        )
        row_height = inputs.addDistanceValueCommandInput(
            "row_height_0",
            "Row 1 Height",
            defultRectSize,
        )
        column_width = inputs.addDistanceValueCommandInput(
            "column_width_0",
            "Column 1 Width",
            defultRectSize,
        )

        rowsTable.addCommandInput(row_number, 1, 0,)
        columnsTable.addCommandInput(column_number, 1, 0)
        rowsTable.addCommandInput(row_height, 1, 1)
        columnsTable.addCommandInput(column_width, 1, 1)

        #optional costume rectangles
        customGrid = inputs.addBoolValueInput(
            "customGrid", "customGrid", True, "", False
        )

        rectanglesTable = inputs.addTableCommandInput("rectanglesTable", "Table", 5, "1:1")

        rectanglesTable.tablePresentationStyle = (
            adsk.core.TablePresentationStyles.itemBorderTablePresentationStyle
        )

        add_button_rectangles = inputs.addBoolValueInput(
            "rectanglesTable_AddButton", "➕", False
        )
        rectanglesTable.addToolbarCommandInput(add_button_rectangles)
        add_button_rectangles.isVisible = False

        for i in range(4):
            cord_input = inputs.addIntegerSpinnerCommandInput(
                f"cord_{i}_0", f"Cord {i},0", 1, maxCount, 1, 1
            )
            rectanglesTable.addCommandInput(cord_input, 0, i)

        # for each one should it be filled or a pocket
        # Create a drop-down input and add it to the first row and second column.
        pocketOrFill = inputs.addDropDownCommandInput(
            "dropList_0", "", adsk.core.DropDownStyles.TextListDropDownStyle
        )
        pocketOrFill.listItems.add("pocket", True, "Resources/Icons/pocket")
        pocketOrFill.listItems.add("filled", False, "Resources/Icons/filled")
        rectanglesTable.addCommandInput(pocketOrFill, 0, 5)

        inputs.addDistanceValueCommandInput(
            "innerFilletRadius",
            "Inner Fillet Radius",
            adsk.core.ValueInput.createByReal(0.25),
        )
        inputs.addDistanceValueCommandInput(
            "outerFilletRadius",
            "Outer Fillet Radius",
            adsk.core.ValueInput.createByReal(1),
        )
        

        # Connect to the execute event.
        onExecute = MakeGridCommandExecuteHandler()
        cmd.execute.add(onExecute)
        handlers.append(onExecute)

        # Connect to the inputChanged event.
        onInputChanged = MakeGridCommandInputChangedHandler()
        cmd.inputChanged.add(onInputChanged)
        handlers.append(onInputChanged)