import os
import textwrap

from PIL import Image, ImageDraw, ImageFont, UnidentifiedImageError

from poizonstore.settings import BASE_DIR


def create_preview(source_image: str, size=None, price_rub=None, title=None):
    def get_font(font_size):
        font_path = os.path.join(BASE_DIR, 'static', 'preview_image_font.ttf')
        return ImageFont.truetype(font_path, size=font_size)

    def resize_with_ar(image, size):
        max_w, max_h = size

        if image.height > image.width:
            factor = max_h / image.height
        else:
            factor = max_w / image.width

        return image.resize((int(image.width * factor), int(image.height * factor)))

    if not os.path.isfile(source_image):
        return None

    # Create image
    preview_width, preview_height = 800, 600
    hor_padding = 15
    vert_padding = 50

    canvas_img = Image.new('RGBA', (preview_width, preview_height), color='white')
    draw = ImageDraw.Draw(canvas_img)

    # Draw top text
    top_font = get_font(20)
    text = 'Заказ в Poizon Store'
    draw.text((hor_padding, vert_padding), text, font=top_font, fill='black')

    # Draw title
    if title:
        title_font = get_font(40)
        text = title
        wrapped_text = textwrap.wrap(text, width=10)

        x, start_y = hor_padding, vert_padding + 30
        for line in wrapped_text:
            draw.text((x, start_y), line, font=title_font, fill='black')
            start_y += title_font.getbbox(line)[3]

    # Draw size
    if size:
        size_text = str(size)
        size_font = get_font(20)
        x1, y1 = hor_padding, vert_padding + 30 + 100
        x2, y2 = x1 + 40, y1 + 40
        draw.rectangle((x1, y1, x2, y2), fill='black', width=2)
        draw.text((x1 + 7, y1 + 7), size_text, font=size_font, fill='white')

    # Draw price
    if price_rub:
        price_text = f"{str(price_rub)} ₽"
        price_font = get_font(50)
        draw.text((hor_padding + 15, preview_height - 100), price_text, font=price_font, fill='black')

    # Draw goods image
    img2_box_w = preview_width - 270 - hor_padding * 2
    img2_box_y = preview_height - vert_padding * 2

    try:
        with Image.open(source_image).convert("RGBA") as img2:
            img2 = resize_with_ar(img2, (img2_box_w, img2_box_y))

            img2_x = 270 + int(img2_box_w / 2) - int(img2.width / 2)
            img2_y = 50 + int(img2_box_y / 2) - int(img2.height / 2)

            canvas_img.paste(img2, (img2_x, img2_y), mask=img2)
            return canvas_img.convert('RGB')
    except UnidentifiedImageError:
        return None


def concat_not_null_values(*values, separator=' '):
    return separator.join([v for v in values if v is not None])
