from qtpy import QtWidgets
from ..backend import themeing_constants, textformatting
from ..globals import pointers

class ToolBarComboBox(QtWidgets.QComboBox):

    def __init__(self):
        super().__init__()
        self.actions_dict = dict()
        #

    def addAction(self, item):
        text = item.text()
        self.addItem(text)
        index = self.findText(text)
        self.actions_dict[index] = item

    def on_index_change(self, index):
        target = self.actions_dict.get(index)
        if target:
            target.trigger()
        pointers.textedit().textChanged.emit()
        pointers.textedit().highlighter.rehighlight()
        pointers.textedit().cursorPositionChanged.emit()

    def block_state(self, state):
        target = None
        for k, v in self.actions_dict.items():
            if hasattr(v, 'assoc_block'):
                if v.assoc_block == state:
                    target = k
                    break
        try:
            self.currentIndexChanged.disconnect()
        except TypeError:
            pass

        if target:
            self.setCurrentIndex(target)
        else:
            self.setCurrentIndex(0)

        self.currentIndexChanged.connect(self.on_index_change)
