import sys

from django.core.management import BaseCommand
from PIL import Image
from PIL.PngImagePlugin import PngImageFile

from oscar.apps.catalogue.models import MissingProductImage
from oscar.core.loading import get_model

ProductImage = get_model("catalogue", "ProductImage")
Category = get_model("catalogue", "Category")


def set_matte(image, matte):
    try:
        if not isinstance(image, MissingProductImage):
            pilimage = Image.open(image)
            if isinstance(pilimage, PngImageFile):
                new_pic = Image.new("RGB", pilimage.size, matte)
                rgba_png = pilimage.convert("RGBA")
                new_pic.paste(rgba_png, rgba_png)
                image.close()
                with image.open("wb") as target_image:
                    new_pic.save(target_image)
                new_pic.close()

            pilimage.close()
            image.close()
    except OSError as e:
        sys.stderr.write("Broken image found %s, %s\n" % (image, e))


class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument(
            "--matte", default="#ffffff", help="Color as a hexadecimal string."
        )

    def handle(self, *args, **options):
        hexstr = options["matte"].strip("#")
        r, g, b = int(hexstr[:2], 16), int(hexstr[2:4], 16), int(hexstr[4:], 16)

        for image in ProductImage.objects.all():
            set_matte(image.original, (r, g, b))

        for category in Category.objects.all():
            if category.image:
                set_matte(category.image, (r, g, b))
