import io
import os
import pathlib
import re
from PIL import Image
from PIL import ImageTk

# TODO: use base64


class PwpBioImage:
    def __init__(self, content: io.BytesIO, img_format: str, filename: str):
        self.buffer = content
        self.img_format = img_format
        self.filename = filename

    def image(self):
        return Image.open(self.buffer)

    def tk_bitmap(self):
        return ImageTk.BitmapImage(Image.open(self.buffer))

    def tk_photo(self):
        return ImageTk.PhotoImage(Image.open(self.buffer))


class PwpEmbedder:

    def __init__(self):
        pass

    def strip(self, name: str):
        return

    @staticmethod
    def convert_data(inf, in_file: str, out_file: str, img_format: str):
        image_name = re.sub(r"[^a-zA-Z0-9_@~àâäéèêëïîôöùûüÿçñÀÂÄÉÈÊËÏÎÔÖÙÛÜŸÇÑ]",
                            "_",
                            os.path.basename(in_file))
        with open(out_file, "w", encoding="utf8") as ouf:
            print(f"# file generated by pwpImageEmbedder from {in_file}\n", file=ouf)
            print("import io\n", file=ouf, end='')
            print("from piwiPre.pwpImageEmbedder import PwpBioImage\n", file=ouf)

            line = f'{image_name} = PwpBioImage(io.BytesIO('
            header = " " * len(line)
            chunk = inf.read(2048)
            buff = b''
            while chunk:
                for i in range(0, len(chunk)):
                    if len(f"{line}{buff+chunk[i:i+1]}") > 119:
                        print(f"{line}{buff}\t# noqa",  file=ouf, end='\n')
                        line = header
                        buff = chunk[i:i+1]
                    else:
                        buff += chunk[i:i+1]
                chunk = inf.read(2048)

            print(f'{line}{buff}),\t# noqa\n', file=ouf, end='')
            line = f'{image_name} = ('
            header = " " * len(line)
            print(f'{header}img_format="{img_format}",\t# noqa\n', file=ouf, end='')
            print(f'{header}filename="{in_file}")\t# noqa\n', file=ouf, end='')

    def convert(self, in_file: str, out_file: str):
        with open(in_file, "rb") as inf:
            img_format = pathlib.Path(in_file).suffix[1:]
            self.convert_data(inf, in_file, out_file, img_format)

    def resize_and_convert(self, in_file: str, out_file: str, width: int, height: int):
        src = Image.open(in_file)
        img_format = pathlib.Path(in_file).suffix[1:]
        src.thumbnail((width, height), resample=Image.LANCZOS)
        buffer = io.BytesIO()
        src.save(buffer, format=img_format)
        b3 = io.BytesIO(buffer.getvalue())
        self.convert_data(b3, in_file, out_file, img_format)


if __name__ == "__main__":
    embedder = PwpEmbedder()
    embedder.resize_and_convert("../pwpLogo.png", "../piwiPre/pwpLogoSmall.py", 50, 29)
