from geoalchemy2.functions import ST_X, ST_Y, ST_Z

from openlog.datamodel.connection.interfaces.read_interface import ReadInterface
from openlog.plugins.connections.bdgeo.database_object import BDGeoCollar


class BDGeoReadInterface(ReadInterface):
    def __init__(self, session):
        """
        Implements ReadInterface for BDGeoConnection

        Args:
            session: sqlalchemy session for BDGeo
        """
        super().__init__()
        self.session = session

    def get_collar_display_name(self, hole_id: str) -> str:
        """
        Get collar display name from hole_id. Get name from bdgeo database

        Args:
            hole_id: str

        Returns: station name

        """
        return (
            self.session.query(BDGeoCollar)
            .filter(BDGeoCollar.hole_id == hole_id)
            .first()
            .name
        )

    def get_collar(self, hole_id: str) -> BDGeoCollar:
        """
        The function `get_collar` returns a collar object for a given hole_id

        :param hole_id: The hole_id of the collar to be updated
        :type hole_id: str
        :return: A Collar object
        """
        # TODO : make it in geoalchemy fashion (see BDGeoCollar definition)
        res = (
            self.session.query(BDGeoCollar)
            .filter(BDGeoCollar.hole_id == hole_id)
            .first()
        )
        x, y, z = self.session.query(
            ST_X(res.geom), ST_Y(res.geom), ST_Z(res.geom)
        ).first()
        setattr(res, "x", x)
        setattr(res, "y", y)
        setattr(res, "z", z)
        return res
