from qgis.core import (
    QgsFeature,
    QgsField,
    QgsGeometry,
    QgsMapLayer,
    QgsMarkerSymbol,
    QgsPoint,
    QgsProject,
    QgsUnitTypes,
    QgsVectorLayer,
)
from qgis.PyQt.QtCore import QItemSelectionModel, QVariant
from qgis.PyQt.QtGui import QColor

from PreCourlis.lib.mascaret.mascaret_file import Section


class PointsSelection:
    def __init__(self):
        self.profiles_layer: QgsVectorLayer = None
        self.section: Section = None
        self.selection_model: QItemSelectionModel = None
        self.memory_layer: QgsVectorLayer = None

    def open(self):
        self.memory_layer = QgsVectorLayer(
            "Point?",
            "Selected points",
            "memory",
        )

        self.memory_layer.dataProvider().addAttributes(
            [
                QgsField("id", QVariant.Int),
                QgsField("abs_lat", QVariant.Double),
            ]
        )
        self.memory_layer.updateFields()

        symbol = QgsMarkerSymbol.createSimple({"name": "circle"})
        symbol.setSize(10.0)
        symbol.setSizeUnit(QgsUnitTypes.RenderPoints)
        symbol.symbolLayer(0).setFillColor(QColor(31, 120, 180, 0))
        symbol.symbolLayer(0).setStrokeWidth(1.0)
        symbol.symbolLayer(0).setStrokeWidthUnit(QgsUnitTypes.RenderPoints)
        symbol.symbolLayer(0).setStrokeColor(QColor(31, 120, 180))
        self.memory_layer.renderer().setSymbol(symbol)

        # Not available before QGIS 3.18
        try:
            self.memory_layer.setFlags(QgsMapLayer.Private)
        except AttributeError:
            pass

        QgsProject.instance().addMapLayer(self.memory_layer)

    def close(self):
        QgsProject.instance().removeMapLayer(self.memory_layer)

    def set_profiles_layers(self, layer: QgsVectorLayer):
        self.profiles_layer = layer
        self.memory_layer.setCrs(layer.crs())

    def set_section(self, section: Section):
        self.section = section
        self.clear()

    def set_selection_model(self, selection_model: QItemSelectionModel):
        if self.selection_model is not None:
            self.selection_model.selectionChanged.disconnect(self.selection_changed)
        self.selection_model = selection_model
        self.selection_model.selectionChanged.connect(self.selection_changed)

    def selection_changed(self, selected, deselected):
        self.refresh()

    def clear(self):
        self.memory_layer.dataProvider().truncate()
        self.memory_layer.reload()

    def refresh(self):
        self.memory_layer.dataProvider().truncate()

        rows = set()
        for index in self.selection_model.selection().indexes():
            rows.add(index.row())

        features = []
        for row in sorted(rows):
            f = QgsFeature()
            f.setFields(self.memory_layer.fields())
            f.setGeometry(
                QgsGeometry(QgsPoint(self.section.x[row], self.section.y[row]))
            )
            f.setAttribute(0, row + 1)
            f.setAttribute(1, float(self.section.distances[row]))
            features.append(f)

        self.memory_layer.dataProvider().addFeatures(features)
        self.memory_layer.reload()
