import json

class ResultAnalyser:
    def __init__(self, vada_result):
        if isinstance(vada_result, str):
            vada_result = json.loads(vada_result)
        self.vada_result = vada_result


    def _to_string(self, msgs):
        strlist = []
        for k, v in msgs:
            if v:
                strlist.append( "[{0}]> {1}".format(k, v) )
        return " ".join(strlist)

    def analyse(self):
        vada_result = self.vada_result
        result = {"status": "SUCCESS", "vada_response": vada_result}

        # Exception: {'status': 'FAILURE', 'vada_response': {
        #     'response': {'timestamp': 1538337058147, 'status': 500, 'error': 'Internal Server Error',
        #                  'exception': 'uk.ac.ox.cs.vada.vadaengine.warded.NotWardedException',
        #                  'message': 'The program is not warded. It cannot be processed.', 'path': '/evaluate'},
        #     'mode': 'run'}, 'error_msg': 'Internal Server Error.  '}

        err_response = vada_result if 'error' in vada_result \
            else vada_result["response"] if 'response' in vada_result and "error" in vada_result["response"] \
                else None

        if err_response:
            error_msgs = []
            if 'message' in err_response:
                error_msgs.append(["MESSAGE", err_response['message']])
            if 'error' in err_response:
                error_msgs.append(["ERROR", err_response['error']])
            if 'exception' in err_response:
                error_msgs.append(["EXCEPTION", err_response['exception']])

            result["status"] = "FAILURE"
            result["error_msg"] = self._to_string(error_msgs)
        else:
            result_set = vada_result.get('resultSet', vada_result.get('response', {}).get('resultSet', None))
            if result_set is not None:
                result['result_set'] = result_set

        # raise Exception(str(result))

        return result
