import json
from typing import (
    Dict,
    Optional,
)

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
        extra=None,         # type: Optional[Dict[str, str]]
    ):
        self.error_code = error_code
        self.error_message = error_message
        self.extra = extra

        data_dict = {
            "errorCode": error_code,
            "errorMessage": error_message,
        }
        if self.extra is not None:
            data_dict.update(self.extra)

        super(ApplicationErrorMessage, self).__init__(
            token=DefaultToken.TK_SYS_APPLICATION_ERROR,
            data_type=DataType.json,
            data=json.dumps(data_dict).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"))
        extra = {}
        for key, value in bad_request_dict.items():
            if key == "errorCode" or key == "errorMessage":
                continue

            extra[key] = value
        if len(extra) == 0:
            extra = None

        return ApplicationErrorMessage(
            error_code=bad_request_dict["errorCode"],
            error_message=bad_request_dict["errorMessage"],
            extra=extra,
        )
