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

__all__ = ['load_dem_rsc', 'load_interferogram', 'load_gdal', 'RSC_KEY_TYPES']

# Cell
import os
import collections
import numpy as np
try:
    import gdal
    _GDAL_INSTALLED = True
except ImportError:
    print("WARNING: gdal not installed, can only load binary '.int' files")
    print("Use 'conda install -c conda-forge gdal' to install for other formats.")
    _GDAL_INSTALLED = False

# Cell

RSC_KEY_TYPES = [
    ("width", int),
    ("file_length", int),
    ("x_first", float),
    ("y_first", float),
    ("x_step", float),
    ("y_step", float),
    ("x_unit", str),
    ("y_unit", str),
    ("z_offset", int),
    ("z_scale", int),
    ("projection", str),
]


def load_dem_rsc(filename, lower=False, **kwargs):
    """Loads and parses the .dem.rsc file
    Args:
        filename (str) path to either the .dem or .dem.rsc file.
            Function will add .rsc to path if passed .dem file
        lower (bool): make keys of the dict lowercase
    Returns:
        dict: dem.rsc file parsed out, keys are all caps
    example file:
    WIDTH         10801
    FILE_LENGTH   7201
    X_FIRST       -157.0
    Y_FIRST       21.0
    X_STEP        0.000277777777
    Y_STEP        -0.000277777777
    X_UNIT        degrees
    Y_UNIT        degrees
    Z_OFFSET      0
    Z_SCALE       1
    PROJECTION    LL
    """

    # Use OrderedDict so that upsample_dem_rsc creates with same ordering as old
    output_data = collections.OrderedDict()
    # Second part in tuple is used to cast string to correct type

    rsc_filename = (
        "{}.rsc".format(filename) if not filename.endswith(".rsc") else filename
    )
    with open(rsc_filename, "r") as f:
        for line in f.readlines():
            for field, num_type in RSC_KEY_TYPES:
                if line.startswith(field.upper()):
                    output_data[field] = num_type(line.split()[1])

    if lower:
        output_data = {k.lower(): d for k, d in output_data.items()}
    return output_data


def load_interferogram(filename, dtype=np.complex64, columns=None, rsc_file=None, band=1):
    """Load binary complex interferogram file.

    Can either pass the number of columns, or a .rsc file with metadata
    """
    if not filename.endswith(".int"):
        return load_gdal(filename, band=band)

    data = np.fromfile(filename, dtype)
    if columns is None:
        if rsc_file is None:
            try:
                rsc_file = filename + ".rsc"
                assert os.path.exists(rsc_file)
                rsc_data = load_dem_rsc(rsc_file, lower=True)
                columns = rsc_data["width"]
            except AssertionError:
                raise ValueError(
                    f"columns or rsc_file not passed, {filename + '.rsc'} does not exist."
                )

    return data.reshape((-1, columns))


def load_gdal(filename, band=1):
    """If not loading a binary .int file, try using GDAL"""
    if not _GDAL_INSTALLED:
        raise ValueError(
            "gdal needed to load filetypes other than '.int'."
            " Use 'conda install -c conda-forge gdal' to install for other formats."
        )
    ds = gdal.Open(filename)
    band = ds.GetRasterBand(band)
    image = band.ReadAsArray()
    band, ds = None, None
    return image