from giara.confManager import ConfManager
from PIL import Image, ImageFilter
from pathlib import Path
from subprocess import Popen
from giara.path_utils import sha256sum


confman = ConfManager()


def make_thumb(path, width: int, height: int = 1000) -> str:
    if not path:
        return None
    if not isinstance(path, Path):
        path = Path(path)
    dest = confman.thumbs_cache_path.joinpath(f'{width}x{height}_{path.name}')
    if dest.is_file():
        return str(dest)
    try:
        with Image.open(path) as thumb:
            thumb = Image.open(path)
            thumb.thumbnail((width, height), Image.ANTIALIAS)
            thumb.save(dest, 'PNG')
        return str(dest)
    except IOError:
        print(f'Error creating thumbnail for image `{path}`')
        return None


def make_video_thumb(path) -> str:
    if not path:
        return None
    if not isinstance(path, Path):
        path = Path(path)
    dest = confman.thumbs_cache_path.joinpath(
        f'{sha256sum(str(path))}_upload_thumb.png'
    )
    command = ' '.join([
        'ffmpeg', '-y',
        '-i', f'"{path}"',
        '-ss', '00:00:01.000',
        '-vframes', '1',
        f'"{dest}"'
    ])
    p = Popen(
        command,
        shell=True
    )
    p.wait()
    return str(dest)


def blur_image(path) -> str:
    if not path:
        return None
    if not isinstance(path, Path):
        path = Path(path)
    dest = confman.thumbs_cache_path.joinpath(
        f'{path.stem}_blur.png'
    )
    try:
        with Image.open(str(path)) as img:
            blurred = img.filter(ImageFilter.GaussianBlur(60))
            blurred.save(dest, 'PNG')
            blurred.close()
        return dest
    except IOError:
        print(f'Error creating blur for image `{path}`')
        return None
