import logging


# Uncomment for debug purpose.
# Use 'all' or specific 'io', 'dsp', 'msgproc', 'secmod', 'mibbuild', 'mibview', 'mibinstrum', 'acl', 'proxy', 'app'
# debug.setLogger(debug.Debug('all'))

#
# Main Class used for recording results
#
class RecordTestStep:
    class StepData:
        def __init__(self, _desc, _result, _error, _expected):
            self.step = dict()
            self.step['desc'] = _desc
            self.step['result'] = _result
            self.step['error'] = _error
            self.step['expected'] = _expected

        def get(self):
            return self.step

    class SessionData:
        def __init__(self, _desc, _pass, _error, _first, _last):
            self.test = dict()
            self.test['name'] = _desc
            self.test['pass'] = _pass
            self.test['fail'] = _error
            self.idx_first = _first
            self.idx_last = _last

        def get(self):
            return self.test

    def __init__(self):
        self.__step_data = []
        self.__test_session = []
        self.prev_idx = 0

    def add_step(self, desc, result, error, expected):
        self.__step_data.append(self.StepData(desc, result, error, expected).get())

    def get_db_session(self):
        return self.__test_session

    def get_db(self):
        return self.__step_data

    def close_session(self, name: str):
        db_step = self.__step_data[self.prev_idx:]
        te = lambda x: 1 if x['result'] and x['error'] is None and x['expected'] is None else 0
        va = lambda x, y: 1 if x['result'] == y else 0
        text = sum(te(i) for i in db_step)
        ok = sum(va(i, True) for i in db_step) - text
        nok = sum(va(i, False) for i in db_step)
        idx = len(self.__step_data)
        self.__test_session.append(self.SessionData(name, ok, nok, self.prev_idx, idx))
        self.prev_idx = idx
        if (ok + nok) > 0:
            logging.warning('Session: {}\r\nTotal Step {}: Success {} ({:.02f}%), Failed {} ({:.02f}%),'
                            .format(name, ok + nok, ok, 100 * ok / (ok + nok), nok, 100 * nok / (ok + nok)))


theRecorder = RecordTestStep()
