import logging

from vkwave.bots import BaseMiddleware, BotEvent, MiddlewareResult, SimpleBotEvent
from vkwave.types.bot_events import GroupJoinObject, MessageNewObject
from vkwave.types.objects import UsersUser

from db import DB, Candidate


async def get_user(api_ctx, user_id):
    raw_user = (
        await api_ctx.api_request("users.get", {"user_ids": user_id})
    )["response"][0]
    return UsersUser(**raw_user)


class UserMiddleware(BaseMiddleware):
    async def pre_process_event(self, event: BotEvent) -> MiddlewareResult:
        db = DB()

        if isinstance(event.object.object, GroupJoinObject):
            user_id = event.object.object.user_id
        elif isinstance(event.object.object, MessageNewObject):
            user_id = event.object.object.message.from_id
        else:
            return MiddlewareResult(True)

        user = db.get_user(user_id)
        if not user:
            user_info = await get_user(event.api_ctx, user_id)
            logging.debug(f"Got user info: {user_info}")
            user = Candidate(id=user_id, sex=user_info.sex, name=user_info.first_name, last_name=user_info.last_name)
            db.add_candidate(user)
            logging.debug(f"Created new user: {user}")
        print(f"Found user: {user}")

        event["current_user"] = user
        return MiddlewareResult(True)
