import numpy as np
import xarray as xr

from cropclass.features.inference import FeaturesComputer


__all__ = ['FeaturesComputer']


def tsteps(x, n_steps=6):
    '''Method to compute tsteps features. In case of
    uint16 inputs, 0 is assumed to be nodata.
    '''
    da = xr.DataArray(x, dims=('t', 'x', 'y'))
    dtype = da.dtype
    if dtype == 'uint16':
        da = da.astype('float32')
        da.values[da.values == 0] = np.nan
    elif dtype == 'float32':
        pass
    else:
        raise TypeError((f'Unsupported dtype `{dtype}` '
                         'for tsteps function.'))

    da_resampled = da.groupby_bins('t', bins=n_steps).mean()

    if dtype == 'uint16':
        da_resampled.values[np.isnan(da_resampled.values)] = 0
        da_resampled = da_resampled.astype(dtype)

    return da_resampled.values


def to_db(pwr):
    return 10 * np.log10(pwr)


def to_pwr(db):
    return np.power(10, db / 10)


def divide_10000(dn):
    return dn.astype(np.float32) / 10000.


def divide_100(dn):
    return dn.astype(np.float32) / 100.
