import json
import logging

from vkwave.bots import DefaultRouter, SimpleBotEvent, PayloadContainsFilter
from vkwave.bots import Keyboard
from vkwave.bots import EventTypeFilter, BotEvent
from vkwave.types.bot_events import BotEventType
import locales
from config import Config
from db import DB

from util.redis_db import RedisDB
from util.nft_util import get_image

test_router = DefaultRouter()

EMPTY_KB = '{"buttons": [], "inline": false, "one_time": false}'


@test_router.registrar.with_decorator(
    EventTypeFilter(BotEventType.MESSAGE_NEW.value),
    PayloadContainsFilter("test"),
)
async def main_part_handle(event: BotEvent):
    user_id = event.object.object.message.from_id
    payload = json.loads(event.object.object.message.payload)

    botevent = SimpleBotEvent(event)
    state_idx = int(payload["test"])
    logging.debug(f"State index: {state_idx}")

    q_res = payload['q'] if 'q' in payload else event.object.object.message.text
    logging.debug(f"Qres: {q_res}")

    # extra_state_data works as fsm.add_data(..., state_data={"name": event.object.object.message.text})
    logging.debug(f"Got text: {event.object.object.message.text}")

    if q_res:
        DB().update_test_result(user_id, question=state_idx, answer=q_res)

    if state_idx + 1 < len(locales.questions):
        RedisDB().set_state(user_id, state_idx + 1)
        kb = locales.questions[state_idx + 1][1]
        if kb:
            return await botevent.answer(
                message=locales.questions[state_idx + 1][0],
                keyboard=kb.get_keyboard(),
            )
        else:
            return await botevent.answer(
                message=locales.questions[state_idx + 1][0],
                payload=json.dumps({"test": state_idx + 1}),
                keyboard=EMPTY_KB,  # try to remove keyboard
            )
    else:
        # todo add task to send user an image here
        # Config().nft_sender.add_task()
        RedisDB().del_state(user_id)
        logging.warn("Sending attach!")

        big_attachment = await Config().uploader.get_attachments_from_paths(
            peer_id=user_id,
            file_paths=[get_image(user_id)],
        )
        await Config().api_ctx.messages.send(
            user_id=user_id, attachment=big_attachment, random_id=0
        )
        return await botevent.answer(
            message=locales.LAST_MESSAGE,
            keyboard=locales.LAST_MESSAGE_KB.get_keyboard(),
        )
