import os
from telegram.ext import ConversationHandler, CommandHandler, MessageHandler, filters, CallbackQueryHandler, CallbackContext
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update, InputMediaPhoto
# ACTION_CHOICE, DATE_ENTRY, ADD_CONTENT = range(3)
MEMORY_CHOICE = range(1)


from .basehandler import BaseHandler

class MemoryHandler(BaseHandler):
    def __init__(self, entry_string, models):
        self.models = models
        self.entry_string = entry_string
        self.handler = ConversationHandler(
            entry_points=[CommandHandler(entry_string, self.entry_point, )],
            states={
                MEMORY_CHOICE: [
                    CallbackQueryHandler(self.choose_memory),
                ]

            },
            fallbacks=[],
        )

        self.current_model = None


    async def entry_point(self, update: Update, context: CallbackContext):
        await super().entry_point(update, context)
        if os.getenv("DOCKERIZED", "false") == "true" and os.getenv("CHAT_ID") != str(update.message.chat_id):
            await update.message.reply_text("You are not authorized to use this bot")
            return ConversationHandler.END

        search_string = " ".join(context.args)

        if search_string == '~photo':
            matching_models = self.models.JournalEntry.select().where(self.models.JournalEntry.media_path != "").order_by(self.models.JournalEntry.date)
        else: # searching for text
            matching_models = self.models.JournalEntry.select().where(
                self.models.JournalEntry.text.contains(
                    search_string
                )
            ).order_by(self.models.JournalEntry.date)


        # exit if no memory matches the string
        if len(matching_models) == 0:
            await update.message.reply_text(f"There is no matching memory yet.")
            return ConversationHandler.END

        options = [[InlineKeyboardButton(m.date_pretty, callback_data=i)] for i,m in enumerate(matching_models)]

        keyboard = InlineKeyboardMarkup(options)

        await update.message.reply_text(
            f"Which moment would you like to remember?", reply_markup=keyboard
            )
        
        context.chat_data["kept_matches"] = list(matching_models)
        
        return MEMORY_CHOICE

    async def choose_memory(self, update: Update, context: CallbackContext):
        query = update.callback_query
        ind = int(query.data)
        await query.answer()

        matching_models = context.chat_data["kept_matches"]
        chosen_match = matching_models[ind]

        if chosen_match.media_path:
            # context.bot.sendPhoto()
            await update.effective_message.reply_photo(
                photo = chosen_match.media_path,
                caption=
                    f"On {chosen_match.date_pretty}, "
                    f"{chosen_match.author} wrote: \n"
                    f"{chosen_match.text}"
                )
        else:
            await query.edit_message_text(
                f"On {chosen_match.date_pretty}, "
                f"{chosen_match.author} wrote: \n"
                f"{chosen_match.text}"
            )

        return ConversationHandler.END