import json

from snek.system.service import BaseService


class UserPropertyService(BaseService):
    mapper_name = "user_property"

    async def set(self, user_uid, name, value):
        self.mapper.db["user_property"].upsert(
            {
                "user_uid": user_uid,
                "name": name,
                "value": json.dumps(value, default=str),
            },
            ["user_uid", "name"],
        )

    async def get(self, user_uid, name):
        try:
            return json.loads(
                (await super().get(user_uid=user_uid, name=name))["value"]
            )
        except Exception as ex:
            print(ex)
            return None

    async def search(self, query, **kwargs):
        query = query.strip().lower()
        if not query:
            raise []
        results = []
        async for result in self.find(name={"ilike": "%" + query + "%"}, **kwargs):
            results.append(result)
        return results
