import os

from app.exceptions import OpenFileError, SubprocessError
from app.paths import COMMONS_DIR
from app.utils.subprocessing import subprocess_call


def check_ffmpeg() -> None:
    """
    Check if ffmpeg is installed.
    :return:
    """
    ffmpeg_binary = get_executable()
    cmd = [ffmpeg_binary, "-version"]
    try:
        subprocess_call(cmd)
    except (FileNotFoundError, SubprocessError):
        raise OpenFileError("Nainstalujte FFmpeg podle návodu v README.md")


def get_executable() -> str:
    """
    Get path to executable "ffmpeg" file depending on OS.
    :return: string with path to executable file
    """
    if os.name == "nt":
        return str(COMMONS_DIR / "ffmpeg" / "ffmpeg.exe")
    return "ffmpeg"


def ffmpeg_extract_subclip(
    file_path: str,
    t1: float,
    t2: float,
    target_path: str,
) -> None:
    """
    Extracts a subclip of duration (t2-t1) from the video file
    :param file_path: path to the input video file
    :param t1: start time of the subclip
    :param t2: end time of the subclip
    :param target_path: path to the output video file
    :return:
    """
    ffmpeg_binary = get_executable()
    cmd = [
        ffmpeg_binary,
        "-y",
        "-ss",
        "%0.2f" % t1,
        "-i",
        file_path,
        "-t",
        "%0.2f" % (t2 - t1),
        "-map",
        "0",
        "-vcodec",
        "copy",
        "-acodec",
        "copy",
        target_path,
    ]
    subprocess_call(cmd)
