import json
from operator import attrgetter

from asyncpg import Connection
from smb.common.pgswim import SwimEngine

from maps_adv.geosmb.tuner.server.lib.enums import PermissionFlag


class DB(SwimEngine):
    @staticmethod
    async def _set_codecs(con: Connection):
        await con.set_type_codec(
            "jsonb", schema="pg_catalog", encoder=json.dumps, decoder=json.loads
        )
        await con.set_type_codec(
            "permission_flag",
            encoder=attrgetter("name"),
            decoder=lambda x: PermissionFlag[x],
        )
