import json
import logging

from vkwave.bots import BaseMiddleware, BotEvent, MiddlewareResult, SimpleBotEvent, Storage
from vkwave.bots.storage.types import Key
from vkwave.types.bot_events import MessageNewObject

from db import DB, Candidate
from util.redis_db import RedisDB

storage = Storage()


class TestStateMiddleware(BaseMiddleware):
    async def pre_process_event(self, event: BotEvent) -> MiddlewareResult:
        if isinstance(event.object.object, MessageNewObject):
            user_id = event.object.object.message.from_id
        else:
            return MiddlewareResult(True)

        redis_test_state = RedisDB().get_state(user_id)
        logging.debug(event.object.object.message.payload)
        payload_json = json.loads(event.object.object.message.payload) if event.object.object.message.payload else {}

        if 'test' not in payload_json.keys() and (
                 redis_test_state != None):
            logging.debug(f"User {user_id} is in state: {redis_test_state}")
            payload_json["test"] = int(redis_test_state)

        event.object.object.message.payload = json.dumps(payload_json)
        return MiddlewareResult(True)
