import pyqtgraph as pg
from pyqtgraph.parametertree.parameterTypes.list import ListParameter, ListParameterItem
from qgis.PyQt.QtGui import QColor, QIcon, QPainter, QPixmap


class MyListParameterItem(ListParameterItem):
    def _get_color_ramp_icon(self, cr_name: str, width=100, height=100) -> QIcon:
        """
        For a given color ramp name, return corresponding QIcon.
        """
        cmap = pg.colormap.get(cr_name)
        pixmap = QPixmap(width, height)
        painter = QPainter(pixmap)

        n_colors = 20

        for i in range(n_colors):
            color = QColor(*cmap.map(i / n_colors))
            painter.setBrush(color)
            painter.setPen(QColor(0, 0, 0, 0))
            painter.drawRect(i * width // n_colors, 0, width // n_colors, height)

        painter.end()

        return QIcon(pixmap)

    def limitsChanged(self, param, limits):
        # set up forward / reverse mappings for name:value

        if len(limits) == 0:
            limits = [
                ""
            ]  ## Can never have an empty list--there is always at least a singhe blank item.

        self.forward, self.reverse = ListParameter.mapping(limits)
        try:
            self.widget.blockSignals(True)
            val = self.targetValue

            self.widget.clear()
            for k in self.forward:
                self.widget.addItem(k)
                if k == val:
                    self.widget.setCurrentIndex(self.widget.count() - 1)
                    self.updateDisplayLabel()

            for index in range(self.widget.count()):
                cm_name = self.widget.itemText(index)
                icon = self._get_color_ramp_icon(cm_name)
                self.widget.setItemIcon(index, icon)

        finally:
            self.widget.blockSignals(False)


class ColorRampPreviewParameter(ListParameter):
    """
    It is a special ListParameter displaying color ramp preview as icon.
    """

    itemClass = MyListParameterItem
