#!/usr/bin/env python
# encoding: utf-8
"""
Run all scripts in examples on specific sample world.
"""

import sys
import os
import subprocess
import shutil
import tempfile
import glob
import logging

import unittest
try:
    from unittest import skip as _skip
except ImportError:
    # Python 2.6 has an older unittest API. The backported package is available from pypi.
    import unittest2 as unittest

# local modules
import downloadsample

if sys.version_info[0] < 3:
    def _deletechars(text, deletechars):
        """Return string, with the deletechars removed"""
        return filter(lambda c: c not in deletechars, text)
else:
    def _deletechars(text, deletechars):
        """Return string, with the deletechars removed"""
        filter = str.maketrans('', '', deletechars)
        return text.translate(filter)

def _mkdir(dstdir, subdir):
    """Helper function: create folder /dstdir/subdir"""
    os.mkdir(os.path.join(dstdir, os.path.normpath(subdir)))
def _copyglob(srcdir, destdir, pattern):
    """Helper function: copies files from /srcdir/pattern to /destdir/pattern.
    pattern is a glob pattern."""
    for fullpath in glob.glob(os.path.join(srcdir, os.path.normpath(pattern))):
        relpath = os.path.relpath(fullpath, srcdir)
        shutil.copy2(fullpath, os.path.join(destdir, relpath))
def _copyrename(srcdir, destdir, src, dest):
    """Helper function: copy file from /srcdir/src to /destdir/dest."""
    shutil.copy2(os.path.join(srcdir, os.path.normpath(src)), \
                os.path.join(destdir, os.path.normpath(dest)))


class ScriptTestCase(unittest.TestCase):
    """Test Case with helper functions for running a script, and installing a 
    Minecraft sample world."""
    worldfolder = None
    mcregionfolder = None
    anvilfolder = None
    examplesdir = os.path.normpath(os.path.join(__file__, os.pardir, os.pardir, 'examples'))
    def runScript(self, script, args):
        scriptpath = os.path.join(self.examplesdir, script)
        args.insert(0, scriptpath)
        # Ensure we're using the same python version.
        # python = sys.argv[0]
        # args.insert(0, python)
        env = dict(os.environ).copy()
        env['LC_ALL'] = 'C'
        # Open a subprocess, wait till it is done, and get the STDOUT result
        p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
        p.wait()