from behave import *
from shutil import copyfile
import os
from PIL import Image, PngImagePlugin

try:
    from steps.common import Case
except ModuleNotFoundError:
    from common import Case



def add_text_to_png(pngfile, texts: dict[str, str]):
    info = PngImagePlugin.PngInfo()
    for key, value in texts.items():
        info.add_text(key, value)
    im = Image.open(pngfile)
    im.save(pngfile, pnginfo=info)


@given(u'a JPEG image as input')
def step_a_jpg_as_input(context):
    case: Case = context.case
    case.copy_and_set_infile(context.test_images["1200.jpg"])


@given(u'the {size} thumb image file is used as input')
def step_a_thumb_is_used_as_input(context, size):
    case: Case = context.case
    input_path = None
    for path in case.thumb_paths:
        path_elements = path.split("/")
        if size == path_elements[-2]:
            assert input_path is None
            input_path = path
    assert input_path is not None
    case.hard_set_infile(input_path)


@given(u'a 16-bit RGB PNG image as input')
def step_a_16bit_rgb_png_as_input(context):
    case: Case = context.case
    case.copy_and_set_infile(context.test_images["1200_16bit_RGB.png"])


@given(u'thumbs exists for the input in standard DB')
def step_thumbs_for_input_exists_in_std_db(context):
    for size, thumb_path in zip(context.case.sizes, context.case.thumb_paths):
        copyfile(context.test_images["thumb_{}".format(size)], thumb_path)
        add_text_to_png(thumb_path, {"Thumb::MTime": str(context.case.infile_mtime)})
        context.case.prepared_thumbs_mtimes[thumb_path] = os.path.getmtime(thumb_path)


@given(u'some thumbs exist')
def step_some_thumbs_exists_in_std_db(context):
        step_a_jpg_as_input(context)
        step_thumbs_for_input_exists_in_std_db(context)


@given(u'no thumbs exist')
def step_no_thumbs_exist(context):
    case: Case = context.case
    assert len(case.prepared_thumbs_mtimes) == 0
    os.makedirs(case.cache_dir)


@given(u'the default cache directory does not exist')
def step_the_default_cache_dir_does_not_exist(context):
    case: Case = context.case
    assert not os.path.exists(case.cache_dir)
