from django.db import models
from telegram import Update
from telegram.ext import Dispatcher, MessageHandler, Filters, CallbackContext

from bots.models import TelegramBotModuleConfig


class FeedbackChat(models.Model):
    chat_id = models.BigIntegerField()


class FeedbackMessage(models.Model):
    chat = models.ForeignKey(FeedbackChat, on_delete=models.CASCADE, related_name='messages')
    forwarded_chat_id = models.BigIntegerField(db_index=True)
    forwarded_message_id = models.BigIntegerField(db_index=True)


class FeedbackBotModuleConfig(TelegramBotModuleConfig):
    forward_chat_id = models.BigIntegerField()

    MODULE_NAME = 'Feedback'

    def build_dispatcher(self, dispatcher: Dispatcher):
        dispatcher.add_handler(MessageHandler(Filters.chat(chat_id=self.forward_chat_id) & Filters.reply, self.handle_internal_message))
        dispatcher.add_handler(MessageHandler(Filters.private & ~Filters.chat(chat_id=self.forward_chat_id), self.handle_external_message))

    def _get_chat(self, update: Update):
        chat, _ = FeedbackChat.objects.get_or_create(chat_id=update.effective_chat.id)
        return chat

    def handle_internal_message(self, update: Update, ctx: CallbackContext):
        try:
            message = FeedbackMessage.objects.get(forwarded_chat_id=update.effective_message.chat_id,
                                                  forwarded_message_id=update.effective_message.reply_to_message.message_id)
            update.message.copy(message.chat.chat_id)
            FeedbackMessage.objects.create(chat=message.chat, forwarded_chat_id=update.effective_message.chat_id,
                                           forwarded_message_id=update.effective_message.message_id)
        except FeedbackMessage.DoesNotExist:
            update.effective_message.reply_text('I don\'t know in which chat to forward this message')

    def handle_external_message(self, update: Update, ctx: CallbackContext):
        if update.effective_message.text and update.effective_message.text.startswith('/'):
            return
        chat = self._get_chat(update)
        # last_message = FeedbackMessage.objects.filter(chat=chat).last()
        msg = update.message.forward(self.forward_chat_id)
        # msg = update.message.copy(self.forward_chat_id,
        #                           reply_to_message_id=last_message.forwarded_message_id if last_message else None)
        FeedbackMessage.objects.create(chat=chat, forwarded_chat_id=self.forward_chat_id,
                                       forwarded_message_id=msg.message_id)
