# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/05_arng.ipynb.

# %% auto 0
__all__ = ['isarng', 'arngchain', 'try2arng', 'arr2arng', 'df2arng', 'asarng', 'arange']

# %% ../nbs/05_arng.ipynb 6
#| export


# %% ../nbs/05_arng.ipynb 8
from typing import TypeGuard

# %% ../nbs/05_arng.ipynb 10
try: import numpy as np
except ModuleNotFoundError: np = None

# %% ../nbs/05_arng.ipynb 12
from atyp import NPArray, IndexLike, DataFrame
from chck import isarr
from calr import applyfns
# from nlit import INDEX

# %% ../nbs/05_arng.ipynb 14
from .arrs import arrchain, try2arr, asarr

# %% ../nbs/05_arng.ipynb 17
def _safe_idx(x): 
    '''try: x.index except: x'''
    try: return x.index
    except: return x

def _safe_len(x):
    '''try: len(x) except: 1'''
    try: return len(x)
    except: return 1

def isarng(a) -> TypeGuard[NPArray]:
    return isarr(a) and np.all(np.ediff1d(a) == 1)

def arngchain(x, funcs, *args, **kwargs): 
    return applyfns(x, funcs, *args, check=isarng, **kwargs)

def try2arng(a) -> NPArray:
    if isarng(a): return a
    try:
        arange = np.arange(_safe_len(a))
        return arange
    except: return a

def arr2arng(a: IndexLike) -> NPArray:
    if isarng(a): return a
    arange = np.arange(len(asarr(a)))
    return arange

def df2arng(df: DataFrame) -> NPArray:
    if isarng(df): return df
    return arr2arng(_safe_idx(df))

# %% ../nbs/05_arng.ipynb 19
def asarng(a, *args, **kwargs) -> NPArray:    
    if isarng(a): return a
    return arngchain(a, (
            df2arng, 
            arr2arng,
            try2arng,            
        ), *args, **kwargs
    )

# %% ../nbs/05_arng.ipynb 20
def arange(a, *args, **kwargs) -> NPArray: 
    return asarng(a, *args, **kwargs)
