# Copyright (c) 2022 BigRep GmbH
from PyQt6.QtCore import Qt

from UM.Logger import Logger
from UM.Qt.ListModel import ListModel

import cura.CuraApplication  # Imported like this to prevent circular dependencies.
from cura.Machines.ContainerTree import ContainerTree


class MachineVariantModel(ListModel):
    IdRole = Qt.ItemDataRole.UserRole + 1
    MachineVariantNameRole = Qt.ItemDataRole.UserRole + 2
    ContainerNodeRole = Qt.ItemDataRole.UserRole + 3

    def __init__(self, parent = None):
        super().__init__(parent)

        self.addRoleName(self.IdRole, "id")
        self.addRoleName(self.MachineVariantNameRole, "machine_variant_name")
        self.addRoleName(self.ContainerNodeRole, "container_node")

        cura.CuraApplication.CuraApplication.getInstance().getMachineManager().globalContainerChanged.connect(self._update)
        cura.CuraApplication.CuraApplication.getInstance().getMachineManager().machineVariantChanged.connect(self._update)
        self._update()

    def _update(self):
        Logger.log("d", "MachineVariantModel is updating {model_class_name}.".format(model_class_name = self.__class__.__name__))

        global_stack = cura.CuraApplication.CuraApplication.getInstance().getGlobalContainerStack()
        if global_stack is None:
            self.setItems([])
            return

        machine_node = ContainerTree.getInstance().machines[global_stack.definition.getId()]
        if not machine_node.has_machine_variants:
            self.setItems([])
            return

        values = global_stack.definition.getProperty("br_build_surfaces", "options")
        item_list = []
        for machine_variant_name, container_node in machine_node.machine_variants.items():            
            item = {"id": values[machine_variant_name],
                    "machine_variant_name": machine_variant_name,
                    "container_node": container_node
                    }

            item_list.append(item)
        self.setItems(item_list)
