#!/usr/bin/env python

from RECT import *

import sys, os
from clogger import *
import time
from decimal import *
import string

from rectparams import *

def main():
    import unittest
    if len(sys.argv) > 3:
        raise RuntimeError('Too many command line arguments!!!!!!!!!!')

    if len(sys.argv) == 3:
        cfgfile = sys.argv[1]
        cfgfile2 = sys.argv[2]
        config = initialize(cfgfile, cfgfile2)

    elif len(sys.argv) == 2:
        cfgfile = sys.argv[1]
        config = initialize(cfgfile)
    else:
        cfgfile = 'config.yaml'
        config = initialize(cfgfile)


    if 'modules' not in config:
        config['modules'] = ['__main__']
    suite = TestLoader(config).loadTests()
    testDescr = []
    for g in config.keys():

        if (getattr(config[g],'__class__').__name__ == 'list'):
            for h in config[g]:
                if (hasattr(h, "keys")):
                    if h.keys() is ['shares', 'slaves'] or ['slaves', 'shares']:
                        testDescr.append({g : h})

    result = []
    slaves = []
    for name in config['proxies']:
        if ('system' not in config['slaves'][name]):
            config['slaves'][name]['system'] = ''
        slaves.append({name:{'start': config['proxies'][name], 'system': config['slaves'][name]['system']}})


    test_config = []
    test_config.append({'shares': config['shares'], 'slaves': slaves, 'testDescr' : testDescr})

    for i in suite.__iter__():

        startTime = time.time()
        s = unittest.TextTestRunner(verbosity=2).run(i)

        stopTime = time.time()
        timeTaken = stopTime - startTime
        timeStr = str(timeTaken)
        test_result = []
        test_errors = []

        for y in i._tests:
            count1 = 1
            count2 = 1
            for z in  y._tests:
                test_mountOptions = []
                testResult = "<P style='color:green'>OK</P>"

                for i_error in s.errors:
                    if (z == i_error[0]):
                        testResult = "<A href='#error_" + str(count1) + "'><P style='color:red'>ERROR</P></A>"
                        count1 += 1


                for i_fail in s.failures:
                    if (z == i_fail[0]):
                        testResult = "<A href='#fail_" + str(count2) + "'><P style='color:red'>FAIL</P></A>"
                        count2 += 1

                for slave in z.slave_names:
                    test_mountOptions.append( {slave : z.getOption(slave, 'mountOptions', '')})

                test_result.append({'tID' : z.tID, 'testResult' : testResult, 'description' : str(z.shortDescription()).split(" (s")[0], 'test method name': z._testMethodName, 'module name' : z.__module__, 'slaves' : [z.slave_names, test_mountOptions], 'shares' : z.share_names})
        test_errors.append({'errors':s.errors, 'failures': s.failures, 'tests_run': s.testsRun, 'time_run': timeStr})

        result.append((test_result, test_errors))


    o_Log = CLogger()
    o_Log.WriteInfoInTemplate( capture_result = result, capture_config = test_config )


if __name__ == '__main__':
    main()

