import json

from ._Message import Message
from ._DefaultToken import DefaultToken
from ._DataType import DataType


class ApplicationErrorMessage(Message):
    def __init__(
        self,               # type: ApplicationErrorMessage
        error_code,         # type: int
        error_message,      # type: str
    ):
        self.error_code = error_code
        self.error_message = error_message

        super(ApplicationErrorMessage, self).__init__(
            token=DefaultToken.TK_SYS_APPLICATION_ERROR,
            data_type=DataType.json,
            data=json.dumps({
                "errorCode": error_code,
                "errorMessage": error_message,
            }).encode("utf-8"),
        )

    @staticmethod
    def build_from_message(
        message,        # type: Message
    ):
        if message.token != DefaultToken.TK_SYS_APPLICATION_ERROR:
            raise RuntimeError("Can only convert TK_SYS_APPLICATION_ERROR messages")

        bad_request_dict = json.loads(message.data.decode("utf-8"))
        return ApplicationErrorMessage(
            error_code=bad_request_dict["errorCode"],
            error_message=bad_request_dict["errorMessage"],
        )
