from pathlib import Path

from qgis.core import QgsDataSourceUri, QgsVectorLayer

from openlog.datamodel.connection.interfaces.layers_interface import LayersInterface
from openlog.toolbelt import PlgTranslator


class SpatialiteLayersInterface(LayersInterface):
    def __init__(self, file_path: Path):
        """
        Implements LayersInterface for SpatialiteConnection

        Args:
            file_path: spatialite file path
        """
        super().__init__()
        self._file_path = file_path
        self.tr = PlgTranslator().tr

    def get_collar_layer(self) -> QgsVectorLayer:
        """
        Return collar QgsVectorLayer

        In spatialite collar geometry is available in collar geom column

        """
        if self.collar_layer is None:
            uri = self._get_datasource_uri()
            uri.setDataSource("", "collar", "geom")
            self.collar_layer = QgsVectorLayer(
                uri.uri(False), self.get_collar_layer_name(), "spatialite"
            )
            self._set_clamping(self.collar_layer)
        return self.collar_layer

    def get_collar_layer_name(self) -> str:
        """
        Get collar layer name

        Returns: (str) collar layer name

        """
        return self.tr("Collar - [{0}]").format(self._file_path)

    def get_collar_trace_layer(self) -> QgsVectorLayer:
        """
        Return collar trace QgsVectorLayer

        In spatialite collar trace geometry is available in collar geom_trace column

        """
        if self.collar_trace_layer is None:
            uri = self._get_datasource_uri()
            uri.setDataSource("", "collar", "geom_trace")
            self.collar_trace_layer = QgsVectorLayer(
                uri.uri(False), self.get_collar_trace_layer_name(), "spatialite"
            )
            self._set_clamping(self.collar_trace_layer)
        return self.collar_trace_layer

    def get_splitted_trace_layer(self, name: str = "") -> QgsVectorLayer:
        """
        Return splitted trace QgsVectorLayer

        In spatialite collar trace geometry is available in collar geom_trace column

        """

        uri = self._get_datasource_uri()
        uri.setDataSource("", f"{name}_trace", "geom_interval")
        self.splitted_trace_layer = QgsVectorLayer(
            uri.uri(False), f"{name}_trace", "spatialite"
        )
        self._set_clamping(self.splitted_trace_layer)
        return self.splitted_trace_layer

    def get_collar_trace_layer_name(self) -> str:
        return self.tr("Trace - [{0}]").format(self._file_path)

    def _get_datasource_uri(self) -> QgsDataSourceUri:
        """
        Get a QgsDataSourceUri from spatialite file

        Returns: QgsDataSourceUri with current connection parameters

        """
        uri = QgsDataSourceUri()
        uri.setDatabase(str(self._file_path))
        return uri
