import tempfile

from PIL import Image
from telegram import Update
from telegram.ext import Dispatcher, CallbackContext, MessageHandler, Filters

from bots.models import TelegramBotModuleConfig


class StickersBotModuleConfig(TelegramBotModuleConfig):
    MODULE_NAME = 'Stickers'

    def resize_image(self, update: Update, ctx: CallbackContext):
        doc = update.message.document
        if update.message.photo:
            with tempfile.NamedTemporaryFile(suffix='.jpg') as f:
                f.write(update.message.photo[-1].get_file().download_as_bytearray())
                f.seek(0)
                im = Image.open(f).convert('RGBA')
        else:
            if doc.mime_type == 'image/png':
                suffix = '.png'
            elif doc.mime_type == 'image/jpeg':
                suffix = '.jpg'
            else:
                return
            with tempfile.NamedTemporaryFile(suffix=suffix) as f:
                f.write(doc.get_file().download_as_bytearray())
                f.seek(0)
                im = Image.open(f).convert('RGBA')
        width, height = im.size
        long_dimension = max(width, height)
        scale_ratio = 512 / long_dimension
        target_width = int(width * scale_ratio)
        target_height = int(height * scale_ratio)
        if long_dimension == width:
            target_width = 512
        else:
            target_height = 512
        im = im.resize((target_width, target_height), Image.LANCZOS)
        with tempfile.NamedTemporaryFile(suffix='.png') as f:
            im.quantize(method=2).save(f, 'png')
            f.seek(0)
            update.message.reply_document(f, caption=f'{width}x{height} -> {target_width}x{target_height}')

    def build_dispatcher(self, dispatcher: Dispatcher):
        dispatcher.add_handler(MessageHandler(Filters.document, self.resize_image))
        dispatcher.add_handler(MessageHandler(Filters.photo, self.resize_image))
        return dispatcher
