#include "TestThread.h"
#include <iostream>
#include <Datei.h>
#include "Test.h"

using namespace Framework;

TestThread::TestThread()
    : Thread()
{
    abbruch = 0;
    start();
}

void TestThread::abbrechen()
{
    abbruch = 1;
}

typedef Test *( *GetTest )( );

void TestThread::thread()
{
    Datei d;
    d.setDatei( "../Tests/bin" );
    RCArray< Text > *files = d.getDateiListe();
    int anz = files->getEintragAnzahl();
    for( int i = 0; i < anz; i++ )
    {
        Text *name = files->z( i );
        name->insert( 0, "../Tests/bin/" );
        HMODULE dll = LoadLibrary( name->getText() );
        if( !dll )
            std::cerr << "Failed to load Test: " << name->getText() << "\n";
        else
        {
            GetTest createTest = (GetTest)GetProcAddress( dll, "createTest" );
            if( !createTest )
                std::cerr << "Failed to load 'createTest' entry point: " << name->getText() << "\n";
            else
            {
                Test *t = createTest();
                t->init();
                while( 1 )
                {
                    t->run();
                    if( t->failed() )
                    {
                        std::cout << "retry or skip (r/s)?\n";
                        int c;
                        do
                        {
                            c = getchar();
                            if( c == EOF )
                                Sleep( 100 );
                            if( abbruch )
                                c = 's';
                        } while( c == EOF );
                        if( c == 's' )
                            break;
                    }
                    else
                        break;
                    t->destroy();
                    t = createTest();
                    t->init();
                }
                if( !t->failed() )
                    std::cout << "\r0xFF00FF00succsess\n\r0xFFFFFFFF";
                t->destroy();
            }
            FreeLibrary( dll );
        }
        if( abbruch )
            break;
    }
    files->release();
    std::cout << "\r0xFF00FF00tests finished";
}