import json
from io import BytesIO

import imagehash
from PIL import Image
from django.core.management import BaseCommand
from telegram import Bot
from tqdm import tqdm

from bots.modules import QueuedItem


class Command(BaseCommand):
    def handle(self, *args, **options):
        for item in tqdm(QueuedItem.objects.filter(type='photo', image_hash__isnull=True)):
            bot: Bot = item.config.bot.get_bot()
            file = bot.get_file(json.loads(item.args)[0])
            io = BytesIO()
            io.name = 'file.jpg'
            file.download(out=io)
            im = Image.open(io)
            item.image_hash = imagehash.phash(im)
            item.save()
