import os
import sqlite3
from io import BytesIO

from wand.image import Image

RPI_DATABASE = "/var/lib/rpiWebApp/database.db"

MC_DATABASE = "***REMOVED***"

DATABASE = RPI_DATABASE if os.path.exists(RPI_DATABASE) else MC_DATABASE


db = sqlite3.connect(DATABASE)
db.row_factory = sqlite3.Row


def resize_image(image, new_width=256, new_height=256):
    new_image = image
    orig_height = new_image.height
    orig_width = new_image.width
    if orig_height >= orig_width:
        width = int((orig_width / orig_height) * new_height)
        height = new_height
    else:
        height = int((orig_height / orig_width) * new_width)
        width = new_width
    new_image.thumbnail(width, height)
    return new_image


def fix_thumbnails():
    new_height = 256
    new_width = 256
    print("Start fix thumbnail size")
    rows = db.execute("SELECT * FROM comic_thumbnails")
    print("got list of all thumbnails\n")

    for row in rows:
        with Image(blob=row["image"]) as image:
            if image.width > new_width or image.height > new_height:
                print("id:", row["id"], "pageNumber:", row["pageNumber"])
                db.execute(
                    "UPDATE comic_thumbnails SET image=? WHERE id=? AND pageNumber=?",
                    [resize_image(image, new_width, new_height).make_blob(), row["id"], row["pageNumber"]],
                )
                db.commit()


fix_thumbnails()
