
import os
import pytest
import logging


try:
    os.makedirs('/tmp/micropsi_tests/worlds')
except OSError:
    pass
try:
    os.makedirs('/tmp/micropsi_tests/nodenets')
except OSError:
    pass


# override config
import configuration
configuration.RESOURCE_PATH = '/tmp/micropsi_tests'
configuration.SERVER_SETTINGS_PATH = configuration.RESOURCE_PATH + '/server_config.json'
configuration.USERMANAGER_PATH = configuration.RESOURCE_PATH + '/user-db.json'

from micropsi_core import runtime as micropsi

# create testuser
from micropsi_server.micropsi_app import usermanager
usermanager.create_user('Pytest User', 'test', 'Administrator', uid='Pytest User')
user_token = usermanager.start_session('Pytest User', 'test', True)

# reset logging levels
logging.getLogger('system').setLevel(logging.WARNING)
logging.getLogger('world').setLevel(logging.WARNING)
logging.getLogger('nodenet').setLevel(logging.WARNING)

world_uid = 'WorldOfPain'
nn_uid = 'Testnet'


def set_logging_levels():
    logging.getLogger('system').setLevel(logging.WARNING)
    logging.getLogger('world').setLevel(logging.WARNING)
    logging.getLogger('nodenet').setLevel(logging.WARNING)


def pytest_addoption(parser):
    parser.addoption("--engine", action="store", default="dict_engine,theano_engine",
        help="The engine that should be used for this testrun.")


def pytest_generate_tests(metafunc):
    if 'engine' in metafunc.fixturenames:
        metafunc.parametrize("engine", metafunc.config.option.engine.split(','), scope="session")


def pytest_configure(config):
    # register an additional marker
    config.addinivalue_line("markers",
        "engine(name): mark test to run only on the specified engine")


def pytest_runtest_setup(item):
    engine_marker = item.get_marker("engine")
    if engine_marker is not None:
        engine_marker = engine_marker.args[0]
        if engine_marker != item.callspec.params['engine']:
            pytest.skip("test requires engine %s" % engine_marker)


def pytest_runtest_call(item):
    if 'fixed_test_nodenet' in micropsi.nodenets:
        micropsi.revert_nodenet("fixed_test_nodenet")
    for uid in micropsi.nodenets:
        micropsi.reload_native_modules(uid)
    micropsi.logger.clear_logs()
    set_logging_levels()


def pytest_runtest_teardown(item, nextitem):
    if nextitem is None:
        print("DELETING ALL STUFF")
        import shutil
        shutil.rmtree(configuration.RESOURCE_PATH)


@pytest.fixture(scope="session")
def resourcepath():
    return configuration.RESOURCE_PATH


@pytest.fixture()
def nodetype_def():
    return os.path.join(configuration.RESOURCE_PATH, 'nodetypes.json')


@pytest.fixture
def nodefunc_def():
    return os.path.join(configuration.RESOURCE_PATH, 'nodefunctions.py')


@pytest.fixture
def recipes_def():
    return os.path.join(configuration.RESOURCE_PATH, 'recipes.py')


@pytest.fixture(scope="function")
def test_world(request):
    global world_uid
    worlds = micropsi.get_available_worlds("Pytest User")
    if world_uid not in worlds:
        success, world_uid = micropsi.new_world("World of Pain", "Island", "Pytest User", uid=world_uid)

    def fin():
        try:
            micropsi.delete_world(world_uid)
        except:
            pass  # world was deleted in test
    request.addfinalizer(fin)
    return world_uid


@pytest.fixture(scope="function")
def test_nodenet(request, test_world, engine):
    global nn_uid
    nodenets = micropsi.get_available_nodenets("Pytest User") or {}
    if nn_uid not in nodenets:
        success, nn_uid = micropsi.new_nodenet("Testnet", engine=engine, worldadapter="Default", world_uid=test_world, owner="Pytest User", uid='Testnet')
        micropsi.save_nodenet(nn_uid)

    def fin():
        try:
            micropsi.delete_nodenet(nn_uid)
        except:
            pass
    request.addfinalizer(fin)
    return nn_uid


@pytest.fixture(scope="function")
def node(request, test_nodenet):
    res, uid = micropsi.add_node(test_nodenet, 'Pipe', [10, 10], name='N1')
    micropsi.add_link(test_nodenet, uid, 'gen', uid, 'gen')
    return uid

@@ -4,16 +4,30 @@
 port os%0A
+import shutil%0A
 import p
@@ -54,35 +54,37 @@
 %0A%0A%0Atry:%0A    
-os.makedirs
+shutil.rmtree
 ('/tmp/micro
@@ -93,22 +93,16 @@
 i_tests/
-worlds
 ')%0Aexcep
@@ -121,25 +121,17 @@
    pass%0A
-try:%0A    
+%0A
 os.maked
@@ -159,43 +159,60 @@
 sts/
-nodenets')%0Aexcept OSError:%0A    pass
+worlds')%0Aos.makedirs('/tmp/micropsi_tests/nodenets')
 %0A%0A%0A#
@@ -2385,30 +2385,8 @@
 F%22)%0A
-        import shutil%0A
     

delete old test-data if applicable