import json
from operator import attrgetter

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

from maps_adv.geosmb.doorman.server.lib.enums import CallEvent, ClientGender, OrderEvent


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(
            "clientgender",
            encoder=attrgetter("name"),
            decoder=lambda x: ClientGender[x],
        )
        await con.set_type_codec(
            "orderevent", encoder=attrgetter("name"), decoder=lambda x: OrderEvent[x]
        )
        await con.set_type_codec(
            "call_event_type",
            encoder=attrgetter("name"),
            decoder=lambda x: CallEvent[x],
        )
