from qgis.core import QgsGeometry, QgsPoint


class PtopoConst:
    NO_X = None
    NO_Y = None
    NO_Z = None
    UNKNOWN_Z = -9999


class Ptopo:
    __slots__ = ("matricule", "type", "x", "y", "z", "codes", "prec_xy", "prec_z")

    def __init__(
        self,
        matricule: str,
        type: str = "P",
        x: float = None,
        y: float = None,
        z: float = PtopoConst.UNKNOWN_Z,
        codes: str = None,
        prec_xy="C",
        prec_z="C",
    ):
        """Constructor
        :param matricule: ptopo name
        """
        self.matricule = matricule
        self.type = type
        self.x = x
        self.y = y
        self.z = z
        self.codes = codes
        self.prec_xy = prec_xy
        self.prec_z = prec_z

    @staticmethod
    def from_feature(feature) -> "Ptopo":
        """Create a Ptopo from a QgsFeature"""
        ptopo = Ptopo(feature.attribute("matricule"))
        ptopo.type = feature.attribute("type_pt")
        geom = feature.geometry()
        pt = geom.constGet()
        ptopo.x = pt.x()
        ptopo.y = pt.y()
        ptopo.z = pt.z()
        ptopo.prec_xy = feature.attribute("prec_xy")
        ptopo.prec_z = feature.attribute("prec_z")
        ptopo.codes = feature.attribute("codes")
        return ptopo

    @staticmethod
    def to_feature(ptopo: "Ptopo", feature) -> None:
        """Fill a QgsFeature from a Ptopo"""
        feature.setAttribute("matricule", ptopo.matricule)
        feature.setAttribute("type_pt", ptopo.type)
        feature.setAttribute("prec_xy", ptopo.prec_xy)
        feature.setAttribute("prec_z", ptopo.prec_z)
        feature.setAttribute("codes", ptopo.codes)
        if ptopo.z is not None:
            z = ptopo.z
        else:
            z = PtopoConst.UNKNOWN_Z
        geom = QgsGeometry.fromPoint(QgsPoint(ptopo.x, ptopo.y, z))
        feature.setGeometry(geom)
