import os
import string
import secrets
import subprocess
import sys
from hashlib import sha256

def format_file_size(num_bytes: int) -> str:
    size = float(num_bytes)

    for unit in ("KB", "MB", "GB", "TB"):
        size /= 1024
        if size < 1024:
            precision = 1 if size < 10 else 0
            return f"{size:.{precision}f} {unit}"

    return f"{size:.1f} PB"

def format_duration(seconds: float) -> str:
    seconds = int(round(seconds))
    h, rem = divmod(seconds, 3600)
    m, s = divmod(rem, 60)

    if h > 0:
        return f"{h}:{m:02d}:{s:02d}"
    return f"{m:02d}:{s:02d}"


def play_with_system_player(fname: str) -> None:

    if sys.platform.startswith("win"):
        os.startfile(fname)  # pylint: disable=no-member
        return

    if sys.platform == "darwin":
        with subprocess.Popen(["open", fname]) as proc:
            proc.wait()
        return

    with subprocess.Popen(["xdg-open", fname]) as proc:
        proc.wait()

def generate_random_string(length:int = 6) -> str:
    """Returns a random string of given length containing capital letters and digits only"""
    characters = string.ascii_uppercase + string.digits
    lst = [secrets.choice(characters) for _ in range(length)]
    random_string = "".join(lst)
    return random_string


def make_hash(s: str, length: int = 16) -> str:

    h = sha256(
        s.encode("utf-8")
    ).hexdigest()

    if length == -1:
        return h

    return h[:length]
