from redis import Redis

from flyers import lists


class RedisHashMap(object):

    def __init__(self, conn: Redis, key: str):
        self.conn = conn
        self.key = key

    def __setitem__(self, field, value):
        self.conn.hset(self.key, field, value)

    def __getitem__(self, field) -> str:
        return self.decode(self.conn.hget(self.key, field))

    def __delitem__(self, field):
        self.conn.hdel(self.key, field)

    def __contains__(self, field) -> bool:
        return self.conn.hexists(self.key, field)

    def delete(self):
        return self.conn.delete(self.key)

    def keys(self) -> list[str]:
        fields = self.conn.hkeys(self.key)
        if lists.is_emtpy(fields):
            return []
        return [self.decode(k) for k in fields]

    def values(self) -> list[str]:
        values = self.conn.hvals(self.key)
        if lists.is_emtpy(values):
            return []
        return [self.decode(k) for k in values]

    def items(self):
        field_values = self.conn.hgetall(self.key)
        result = {}
        for k, v in field_values.items():
            result[self.decode(k)] = self.decode(v)
        return result

    @staticmethod
    def decode(b: bytes):
        if not b:
            return None
        return bytes.decode(b)
