# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/01_utils.ipynb.

# %% auto 0
__all__ = ['getidx', 'getexp', 'getsuf', 'getnum', 'format']

# %% ../nbs/01_utils.ipynb 5
import os, math
from dataclasses import KW_ONLY, dataclass, field
from enum import Enum, StrEnum, IntEnum
from typing import Union, List, Optional, Iterable

# %% ../nbs/01_utils.ipynb 7
from .units import (KILO, UNITS)
from pstr.nchr.core import SPACE

# %% ../nbs/01_utils.ipynb 9
def getidx(size: int = 1, base: int = KILO, units: Iterable = UNITS) -> int:
    '''Gets the index of the unit for a given size and base'''
    for idx in range(len(units)):
        if size < base ** (idx + 1): return idx
    return idx

def getexp(size: int = 1, base: int = KILO, units: Iterable = UNITS):
    '''Gets the power of the unit for a given size and base'''
    idx = getidx(size, base, units)
    return base ** (idx + 1)

def getsuf(size: int = 1, base: int = KILO, units: Iterable = UNITS):
    '''Returns the unit suffix for a given size and base'''
    idx = getidx(size, base, units)
    return units[idx]

def getnum(size: int = 1, base: int = KILO, precision: Optional[int] = 1, units: Iterable = UNITS):
    '''Returns the unit suffix for a given size and base'''
    expo = getexp(size, base, units)
    numb = float(base * size / expo)
    prec = precision or len(str(numb))
    return round(numb, prec)

def format(size: int = 1, base: int = 1000, sep: Optional[str] = SPACE, precision: Optional[int] = 1, units: Iterable = UNITS):
    sfix = getsuf(size, base, units)
    numb = getnum(size, base, precision, units)
    if size == 1: return '1 byte'
    elif size < base: return f'{size:,} bytes'
    return f'{numb:,.{precision}f}{sep}{sfix}'
