
import pytest
import inspect
import os
    
@pytest.mark.trylast
def pytest_configure(config):
    terminal_reporter = config.pluginmanager.getplugin('terminalreporter')
    try:
        config.pluginmanager.unregister(TestDescriptionPlugin(terminal_reporter), 'testdescription')
    except:
        pass
    config.pluginmanager.register(TestDescriptionPlugin(terminal_reporter), 'testdescription')
        
class TestDescriptionPlugin:

    def __init__(self, terminal_reporter):
        self.terminal_reporter = terminal_reporter
        self.desc = None
        self.funcn = None

    def pytest_runtest_protocol(self, item):
        #from pprint import pprint
        #d = item.__dict__
        #pprint(d, indent=2)
        self.desc = inspect.getdoc(item.obj)
        #print(item._nodeid)
        self.funcn = item._nodeid

    @pytest.hookimpl(hookwrapper=True, tryfirst=True)
    def pytest_runtest_logstart(self, nodeid, location):
        #print("Verbosity Level: {}".format(self.terminal_reporter.verbosity))
        if self.terminal_reporter.verbosity == 0:
            yield
            self.terminal_reporter.write(f'\n{self.funcn} \n')
        else:
            self.terminal_reporter.write('\n')
            yield
            if self.desc:
                    self.terminal_reporter.write(f'\n{self.desc} \n')
            else:
                    self.terminal_reporter.write(f'\n')
    
    @pytest.hookimpl(hookwrapper=True)
    def pytest_runtest_makereport(item, call):
        outcome = yield
        report = outcome.get_result()
        if report.when=='call':
            filepath = os.path.join(os.getcwd(),'short_summary.log')
            # write short summary to file
            file_obj = open(filepath, 'a' if os.path.isfile(filepath) else 'w')
            file_obj.write("{} {}\n".format(report.outcome.upper(), report.nodeid))
            file_obj.close()

            # Write not pass to Textfile
            if report.outcome != 'passed':
                file_obj = open(filepath, 'a' if os.path.isfile(filepath) else 'w')
                file_obj.write("\tDuration: {}s\n".format(round(report.duration,5)))
                if report.outcome == 'failed':
                    file_obj.write("\tMessage : {}\n".format(report.longrepr.reprcrash.message))
                file_obj.close()
                filepath = os.path.join(os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..')),'summary_of_failed.log')
                file_obj = open(filepath, 'a' if os.path.isfile(filepath) else 'w')
                file_obj.write("{} {}\n".format(report.outcome.upper(), report.nodeid))
                file_obj.write("\tDuration: {}s\n".format(round(report.duration,5)))
                if report.outcome == 'failed':
                    file_obj.write("\tMessage : {}\n".format(report.longrepr.reprcrash.message))
                file_obj.close()
    