from api.route import Route
from api_graphql.abc.mutation_abc import MutationABC
from api_graphql.input.user_setting_input import UserSettingInput
from core.logger import APILogger
from data.schemas.public.user_setting import UserSetting
from data.schemas.public.user_setting_dao import userSettingsDao
from data.schemas.system.setting_dao import settingsDao
from service.permission.permissions_enum import Permissions

logger = APILogger(__name__)


class UserSettingMutation(MutationABC):
    def __init__(self):
        MutationABC.__init__(self, "UserSetting")
        self.mutation(
            "change",
            self.resolve_change,
            UserSettingInput,
            require_any_permission=[Permissions.settings_update],
        )

    @staticmethod
    async def resolve_change(obj: UserSettingInput, *_):
        logger.debug(f"create new setting: {input}")
        user = await Route.get_user_or_default()
        if user is None:
            logger.debug("user not authorized")
            return None

        setting = await userSettingsDao.find_single_by(
            [{UserSetting.user_id: user.id}, {UserSetting.key: obj.key}]
        )
        if setting is None:
            await userSettingsDao.create(UserSetting(0, user.id, obj.key, obj.value))
        else:
            setting.value = obj.value
            await userSettingsDao.update(setting)

        return await userSettingsDao.find_by_key(user, obj.key)
