from glob import glob
import os
import uuid

import rasterio
from pyproj import Proj
from jinja2 import Environment, PackageLoader

from madmex.util import s3

def metadata_convert(path, bucket=None):
    """Prepare metadata prior to datacube indexing

    Given a directory containing country mask tiles generated by the make_country_mask command line
    prepares a metadata string with the appropriate formating for indexing in the datacube
    The other ``metadata_convert`` functions assume that datasets are separated in different different
    so that the ``prepare_metadata`` command line handles the optional iteration based on this assumption.
    Because all tiles of a country mask are all in a same folder, iteration has to be handles by the
    present function.

    Args:
        path (str): Path of the directory containing the country mask tiles
        bucket (str or None): Name of the s3 bucket containing the data. If ``None``
            (default), data are considered to be on a mounted filesystem

    Examples:
        >>> from madmex.ingestion.country_mask import metadata_convert
        >>> path = '/path/to/mask/dir'
        >>> yaml_str = metadata_convert(path)
        >>> with open('/path/to/metadata_out.yaml', 'w') as dst:
        >>>     dst.write(yaml_str)

    Returns:
        str: The content of the metadata for later writing to file.
    """
    if bucket is not None:
        file_list = s3.list_files(bucket, path, r'land_mask_tile_\d+.tif$')
        file_list = [s3.build_rasterio_path(bucket, x)
                     for x in file_list]
    else:
        file_list = glob(os.path.join(path, 'land_mask_tile_*.tif'))

    def build_meta_string(x):
        """Generate the yaml string for a single tile

        Args:
            x (str): The path of the dataset
        """
        try:
            with rasterio.open(x) as src:
                crs = src.crs
                bounds = src.bounds
            meta_out = {
                'id': uuid.uuid5(uuid.NAMESPACE_URL, x),
                'll_lat': bounds.bottom,
                'lr_lat': bounds.bottom,
                'ul_lat': bounds.top,
                'ur_lat': bounds.top,
                'll_lon': bounds.left,
                'lr_lon': bounds.right,
                'ul_lon': bounds.left,
                'ur_lon': bounds.right,
                'crs': crs.wkt,
                'band': x,
            }
            # Load template
            env = Environment(loader=PackageLoader('madmex', 'templates'))
            template = env.get_template('country_mask.yaml')
            out = template.render(**meta_out)
            return out
        except Exception as e:
            pass

    yaml_list = [build_meta_string(x) for x in file_list]
    yaml_list = [x for x in yaml_list if x is not None]
    return '\n---\n'.join(yaml_list)
