import requests
from giara.confManager import ConfManager
from giara.path_utils import get_file_extension, sha256sum
from os.path import isfile
from os import remove
from subprocess import Popen

confman = ConfManager()
GET_HEADERS = {
    'User-Agent': 'giara/1.0',
    'Accept': '*/*',
    'Accept-Encoding': 'gzip, deflate'
}
TIMEOUT = 30


def __error_out(link: str, code: int):
    raise requests.HTTPError(
        f'response code {code} for url `{link}`'
    )


def fix_url(link: str) -> str:
    if not link:
        return None
    if link.lower()[:8] != 'https://' and link.lower()[:7] != 'http://':
        if link[0] == '/':  # assume it's a reddit url
            return 'https://reddit.com' + link
        return 'http://' + link
    return link


def download_img(link: str, force_extension: str = None) -> str:
    link = fix_url(link)
    if not link:
        return None
    extension = force_extension or get_file_extension(link)
    dest = f'{confman.cache_path}/{sha256sum(link)}.{extension}'
    if not isfile(dest):
        res = requests.get(link, headers=GET_HEADERS, timeout=TIMEOUT)
        if 200 <= res.status_code <= 299:
            with open(dest, 'wb') as fd:
                for chunk in res.iter_content(1024):
                    fd.write(chunk)
        else:
            # __error_out(link, res.status_code)
            return None
    return dest


def download_video(link: str) -> str:
    link = fix_url(link)
    if not link:
        return None
    dest = f'{confman.cache_path}/{sha256sum(link)}_video_audio.mkv'
    if not isfile(dest):
        extension = get_file_extension(link) or 'mp4'
        video = download_img(link, extension)
        audio = download_img(link[:link.rfind('/')]+'/DASH_audio.mp4', 'mp4')
        if audio is None:
            return video
        command = ' '.join([
            'ffmpeg', '-y',
            '-i', f'"{video}"',
            '-i', f'"{audio}"',
            '-c', 'copy',
            '-map', '0:v:0',
            '-map', '1:a:0',
            '-shortest',
            f'"{dest}"'
        ])
        p = Popen(
            command,
            shell=True
        )
        p.wait()
        remove(video)
        remove(audio)
    return dest
