import sys
if sys.version_info < (3, 9):
    # importlib.resources either doesn't exist or lacks the files()
    # function, so use the PyPI version:
    import importlib_resources
else:
    # importlib.resources has files(), so use that:
    import importlib.resources as importlib_resources
import geopandas
import numpy as np


class RasterData:
    """
    Class to read information from raster maps (geotiff files or similar)
    """

    def __init__(self, map_path, columns):
        """

        Parameters
        ----------

        """
        self.map = geopandas.read_file(map_path)
        if type(columns) == dict:
            self.columns = columns
        if type(columns) == list:
            self.columns = {}
            for col in columns:
                self.columns[col] = col

    def __call__(self, df):
        return self.get_data(df)

    def get_data(self, df):
        """
        Get the features and the bathymetry together of all the DataFrame
        Parameters
        ----------
        df : DataFrame
            Where to add the seabottom test_data
        Returns
        -------
        DataFrame with features added
        """

        df_map = df[['geometry']].sjoin(self.map.to_crs(df.crs)[list(self.columns.keys()) + ['geometry']],
                                        predicate='within')
        for col, col_name in self.columns.items():
            df[col_name] = np.nan
            df.loc[df_map.index, col_name] = df_map[col]
        return df


class SeabedHabitatData(RasterData):
    def __init__(self):
        columns = {'Substrate': 'substrate', 'Allcomb': 'seabed_habitat'}
        seabed_resource = importlib_resources.files('bpnsdata') / 'data' / 'seabedhabitat_BE.shp'
        with importlib_resources.as_file(seabed_resource) as seabed_path:
            super().__init__(seabed_path, columns)


class HabitatSuitabilityData(RasterData):
    """
    Class referencing to the map generated by the publication benthic habitats ([1]V. Van Lancker, G. Moerkerke,
    I. Du Four, E. Verfaillie, M. Rabaut, and S. Degraer, “Fine-scale Geomorphological Mapping of Sandbank Environments
    for the Prediction of Macrobenthic Occurences, Belgian Part of the North Sea,” Seafloor Geomorphology as Benthic
    Habitat, pp. 251–260, 2012, doi: 10.1016/B978-0-12-385140-6.00014-1. )
    """
    def __init__(self):
        columns = {'GRIDCODE': 'benthic_habitat'}
        suitability_resource = importlib_resources.files('bpnsdata') / 'data' / 'Habitat Suitability2.shp'
        with importlib_resources.as_file(suitability_resource) as suitability_path:
            super().__init__(suitability_path, columns)
