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

__all__ = ['get_tile_lat_lon', 'process_cube_tiles']

# Cell

import pandas as pd
import pvl
from dask import compute, delayed
from kalasiris.pysis import ProcessError, campt
from planetarypy.utils import get_gdal_center_coords

# Cell


def get_tile_lat_lon(fname):
    d = {}
    d["fname"] = fname.name
    x, y = get_gdal_center_coords(fname)

    try:
        pvlstr = campt(from_=str(fname), format="pvl", type="image", sample=x, line=y)
    except ProcessError as e:
        print("STDOUT:", e.stdout)
        print("STDERR:", e.stderr)

    pvlstruct = pvl.loads(pvlstr)
    d["lat_centric"] = pvlstruct["GroundPoint"]["PlanetocentricLatitude"].value
    d["lon"] = pvlstruct["GroundPoint"]["PositiveEast360Longitude"].value
    d["lat_graphic"] = pvlstruct["GroundPoint"]["PlanetographicLatitude"].value
    return d

# Cell


def process_cube_tiles(saveroot):
    cubefiles = saveroot.rglob("*.????.cub")
    lazys = []
    for cubefile in cubefiles:
        lazys.append(delayed(get_tile_lat_lon)(cubefile))
    results = compute(*lazys)
    savename = f"lat_lon_for_tiles_{saveroot.name}.csv"
    pd.DataFrame(results).to_csv(saveroot / savename, index=False)