"""
Run several blender instances if blender is installed
"""
import pkg_resources
import glob
import os
import sys
import shutil
import inspect
import tempfile


def activate_virtualenv(venv_path):
    if venv_path is None:
        raise NameError('Python is not running within a virtualenv')
    filepath = os.path.join(venv_path, 'bin', 'activate_this.py')
    with open(filepath, 'r') as f:
        exec(f.read(), dict(__file__=filepath))


venv_path = sys.base_prefix

blendercomand = shutil.which('blender')
worldfile = pkg_resources.resource_filename(
    'navipy', 'resources/forest_world.blend')
encoding = 'utf-8'
for demofile in glob.iglob('**/blenddemo*.py', recursive=True):
    with tempfile.NamedTemporaryFile() as tfile:
        tfile.write('import os \n'.encode(encoding))
        for line in inspect.getsourcelines(activate_virtualenv)[0]:
            tfile.write(line.encode(encoding))
        line = 'activate_virtualenv(\"{}\")\n'.format(venv_path)
        tfile.write(line.encode(encoding))
        with open(demofile) as infile:
            for line in infile:
                tfile.write(line.encode(encoding))
        tfile.seek(0)
        print(tfile.read())
        tfile.seek(0)
        command = '{} {} --background --python {}'.format(
            blendercomand, worldfile, tfile.name)
        os.system(command)