"""
Delete duplicate product images
"""

from collections import defaultdict

from django.core.management.base import BaseCommand

from oscar.core.loading import get_model

from oscarapi.utils.files import file_hash

Product = get_model("catalogue", "Product")


class Command(BaseCommand):
    help = __doc__

    def add_arguments(self, parser):
        parser.add_argument(
            "--no-dry-run", action="store_true", help="Really commit to the database"
        )

    def handle(self, *args, **options):
        for p in Product.objects.filter(images__isnull=False):
            pic_table = defaultdict(list)
            for im in p.images.all():
                p = file_hash(im.original)
                pic_table[p].append(im)

            for imagelist in pic_table.values():
                if len(imagelist) > 1:
                    _, *duplicates = imagelist
                    for duplicate in duplicates:
                        duplicate.delete()
