import json
from typing import Any

from ... import messages as m
from .. import MessageEncoder


class JsonEncoder(MessageEncoder):
    """Encoder of messages for testing purposes"""

    def encode(self, payload: m.Payload) -> str:
        """Convert a payload dict to a string for publishing"""

        return json.dumps(payload.to_dict(), sort_keys=True)

    def decode(self, payload: str) -> m.Payload:
        """Convert payload to a payload dict"""
        payload_map = json.loads(payload)
        if "online" in payload_map:
            return m.HostPayload.from_dict(payload_map)
        else:
            return m.NodePayload.from_dict(payload_map)
