from loguru import logger
import shutil
from pathlib import Path


def download_and_unpack(modeldir: str, modeltag: str):
    import urllib

    modelfile = str(modeldir) + '/' + modeltag
    extract_dir = Path.cwd() / 'tmp' / 'models'
    extract_dir.mkdir(exist_ok=True, parents=True)

    logger.info(f'Downloading modelfile: {modelfile}')
    try:
        modelfile, _ = urllib.request.urlretrieve(
            modelfile, filename=extract_dir / Path(modelfile).name)
    except Exception:
        logger.error(f'Failed to download model from: {modelfile}.')
        raise

    try:
        shutil.unpack_archive(modelfile,
                              extract_dir=extract_dir)
    except Exception:
        logger.error('Failed to extract model archive.')

    return extract_dir, Path(modeltag).stem


def laea20km_id_to_extent(laea_id: str):
    """Method to get extent in EPSG:3035
    from a 20km LAEA grid ID

    Args:
        laea_id: an id, like 'E380N278'

    Returns:

    """

    assert laea_id[0] == 'E'
    assert 'N' in laea_id
    parts = laea_id.lstrip('E').split('N')
    west = int(parts[0]) * 10000
    south = int(parts[1]) * 10000
    # we now have lower-left corner
    return {
        'east': west + 20000,
        'south': south,
        'west': west,
        'north': south + 20000,
        'crs': 'EPSG:3035'
    }
