# AUTOGENERATED! DO NOT EDIT! File to edit: 01_tiling.ipynb (unless otherwise specified).

__all__ = ['skimage_to_png', 'get_savename', 'split_cube_into_tiles', 'convert_to_png_skimage', 'convert_to_png_isis']

# Cell

import warnings
import rasterio
import xarray
warnings.filterwarnings("ignore", category=rasterio.errors.NotGeoreferencedWarning)

# Cell

from skimage.io import imsave
from skimage.util import img_as_ubyte
from skimage.exposure import rescale_intensity
from fastcore.utils import Path

def skimage_to_png(fin):
    data = rasterio.open(fin).read(1)
    rescaled = rescale_intensity(data)
    ubyte = img_as_ubyte(rescaled, out_range='uint8')
    fout = Path(fin).with_suffix(".png")
    imsave(fout, ubyte)
    return rescaled

# Cell

from pathlib import Path

from dask import compute, delayed
from kalasiris.pysis import ProcessError, crop, isis2std


def get_savename(cubname, i, parent=None):
    "Take a path and add a tile number."
    p = Path(cubname)
    parent = p.parent if parent is None else parent
    stem = p.name.split(".")[0]
    return f"{parent / stem}.{str(i).zfill(4)}{p.suffix}"


def split_cube_into_tiles(
    cube_fname,
    nsamples=800,
    nlines=600,
    dataset_folder=None,
    overwrite=False,
):
    ds = rasterio.open(cube_fname)
    i = 0
    # attach product_id folder name to dataset_folder
    parent_folder = dataset_folder / cube_fname.parent.name
    parent_folder.mkdir(parents=True, exist_ok=True)

    lazys = []
    for samples_offset in range(1, ds.width, nsamples):
        if (ds.width - samples_offset) < nsamples:
            break
        for lines_offset in range(1, ds.height, nlines):
            if (ds.height - lines_offset) < nlines:
                break
            fpath = get_savename(cube_fname, i, parent=parent_folder)
            if Path(fpath).exists() and not overwrite:
                continue
            lazys.append(
                delayed(crop)(
                    from_=cube_fname,
                    to=fpath,
                    sample=samples_offset,
                    line=lines_offset,
                    nsamples=nsamples,
                    nlines=nlines,
                )
            )
            i += 1
    compute(*lazys)


def convert_to_png_skimage(folder):
    "Convert all cubes found in a folder to png."
    cubes = folder.glob("*.cub")
    lazys = []
    for cube in cubes:
        lazys.append(delayed(skimage_to_png)(cube))
    compute(*lazys)


def convert_to_png_isis(folder):
    "Convert all cubes found in a folder to png."
    cubes = folder.glob("*.cub")
    lazys = []
    for cube in cubes:
        lazys.append(
            delayed(isis2std)(
                from_=cube,
                to=cube.with_suffix(".png"),
                format="png",
                minpercent=0,
                maxpercent=100,
            )
        )
    compute(*lazys)