
from typing import Optional

from pyproj import CRS as _PyprojCRS


class Crs:
    """Coordinate Reference System, costruibile da EPSG, WKT o PROJ."""

    def __init__(self, definition=None):
        if definition is None or definition == "":
            self._crs = None
        else:
            self._crs = _PyprojCRS.from_user_input(definition)

    @classmethod
    def from_epsg(cls, code: int) -> "Crs":
        return cls(code)

    @classmethod
    def from_wkt(cls, wkt: str) -> "Crs":
        if not wkt:
            return cls()
        return cls(wkt)

    @property
    def is_set(self) -> bool:
        return self._crs is not None

    def to_wkt(self, version="WKT2_2019") -> Optional[str]:
        return self._crs.to_wkt(version) if self._crs else None

    def to_epsg(self) -> Optional[int]:
        """Returns the EPSG code if the CRS has an EPSG authority, else None."""
        if not self._crs:
            return None
        return self._crs.to_epsg()

    def __eq__(self, other) -> bool:
        return isinstance(other, Crs) and self._crs == other._crs

    def __hash__(self) -> int:
        return hash(self._crs)

    def __repr__(self) -> str:
        return f"Crs({self._crs.to_authority() if self._crs else None})"



if __name__ == "__main__":
    import doctest

    doctest.testmod()
