from .common import UnmappedError, ResponseFormatError


def _construct_mapping():
    from .common import CODES as COMMON_CODES
    from .klass import CODES as KLASS_CODES
    from .lab import CODES as LAB_CODES
    from .pod import CODES as POD_CODES
    from .reservation import CODES as RESERVATION_CODES
    from .user import CODES as USER_CODES
    from .vm import CODES as VM_CODES

    result = {}
    for code in COMMON_CODES + KLASS_CODES + LAB_CODES + POD_CODES + RESERVATION_CODES + USER_CODES + VM_CODES:
        assert code.str_error not in result, code.str_error
        result[code.str_error] = code

    return result


NAME_CODE_MAPPING = _construct_mapping()


def error_decode(e):
    if not isinstance(e, dict):
        return ResponseFormatError()

    error_code = e['message']
    try:
        error_data = e['data']['message']
    except KeyError:
        error_data = None

    if error_code in NAME_CODE_MAPPING:
        return NAME_CODE_MAPPING[error_code](error_data)
    else:
        return UnmappedError(error_code, error_data)
