# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/10_exts.ipynb.

# %% auto 0
__all__ = ['dotstr', 'predot', 'insert_exts', 'hasext', 'dropext', 'istar', 'isgz', 'istargz', 'istarball', 'isavi']

# %% ../nbs/10_exts.ipynb 5
from pathlib import Path

# %% ../nbs/10_exts.ipynb 7
from nchr import DOT, NIL
from nlit import EXT_TAR, EXT_GZ, EXT_TAR_GZ, EXT_AVI
from quac import pathlike, strq
from atup import vargs

# %% ../nbs/10_exts.ipynb 9
from .util import fspath, dirfile

# %% ../nbs/10_exts.ipynb 11
def dotstr(*strs: str, nils: bool = False) -> str:
    strs= tuple(map(str, tuple(vargs(strs))))
    strs = tuple(filter(lambda s: s, strs)) if (not nils) else strs
    return DOT.join(strs)

def predot(*strs: str) -> str: 
    return dotstr(NIL, *strs)

# %% ../nbs/10_exts.ipynb 12
def insert_exts(
    path: pathlike, *exts: str, 
    idx: int = -1, extchr: str = DOT
) -> pathlike:
    path = Path(path)
    parts = path.name.split(extchr)
    
    dotparts = list(predot(p) for p in parts[1:])
    fullexts = NIL.join(predot(p) for p in exts)

    hasext = any(map(lambda p: p in fullexts, dotparts))

    if hasext:
        for i, dotpart in enumerate(dotparts):
            if not fullexts.startswith(dotpart): continue
            idx = i + 1
            fullexts = fullexts.removeprefix(dotpart)

        dotparts.insert(idx, fullexts)
    else:
        if idx == -1: idx = len(dotparts)
        elif idx < 0: idx += 1    
        dotparts.insert(idx, fullexts)
    final = NIL.join((parts[0], *dotparts))
    return path.with_name(final)

# %% ../nbs/10_exts.ipynb 13
def hasext(file: str, ext: strq = None) -> bool:
    file = fspath(file)
    return ext in file and file.endswith(ext)

# %% ../nbs/10_exts.ipynb 14
def dropext(file: pathlike, ext: strq = None) -> str:
    path, name = dirfile(file)
    name = name.partition(DOT)[0] if ext is None else name.removesuffix(ext)#.replace(ext, NIL)
    return path / name

# %% ../nbs/10_exts.ipynb 15
def istar(file: str) -> bool:
    return hasext(file, EXT_TAR)

def isgz(file: str) -> bool:
    return hasext(file, EXT_GZ)

def istargz(file: str) -> bool:
    return hasext(file, EXT_TAR_GZ)

def istarball(file: str) -> bool:
    return istar(file) or istargz(file)

# %% ../nbs/10_exts.ipynb 16
def isavi(file: str) -> bool:
    return hasext(file, EXT_AVI)
