import sys
import shutil

from os import sep, listdir, unlink, makedirs
from os.path import join, isdir, dirname, abspath, expanduser, exists

from .utils import compute_checksums


def get_repo_api(config):
    name = oname = config.dest_channel.rstrip("/")
    if config.dest_site:
        name = join(config.dest_site, name)
    if sep != "/":
        name = name.replace("/", sep)
    name = abspath(expanduser(name))
    base = name[: -len(oname) - 1]
    return (base,)


def _join(*args):
    return join(*(a for a in args if a))


def list_objects(base, *path, repodata=None):
    dname = _join(*base, *path)
    packages = {}
    for fn in listdir(dname) if exists(dname) else ():
        fpath = join(dname, fn)
        if not isdir(fpath):
            packages[fn] = compute_checksums(fpath)
    return packages


def get_object(base, *path):
    fpath = _join(*base, *path)
    if exists(fpath):
        with open(fpath, "rb") as fp:
            return fp.read()


def del_object(base, *path, metadata=None):
    fpath = _join(*base, *path)
    if exists(fpath):
        unlink(fpath)
    if len(path) > 2:
        dname = dirname(fpath)
        if isdir(dname) and not listdir(dname):
            shutil.rmtree(dname, ignore_errors=True)


def put_object(base, *path, path_or_data=None, metadata=None):
    fpath = _join(*base, *path)
    makedirs(dirname(fpath), exist_ok=True)
    if isinstance(path_or_data, bytes):
        with open(fpath, "wb") as fp:
            fp.write(path_or_data)
    else:
        shutil.copyfile(path_or_data, fpath)


def main():
    from .common import main as _main

    _main(sys.modules[__name__])
