import glob
import subprocess
from threading import Timer
import logging
import distutils.dir_util
import sys
import multiprocessing
import os
from shutil import copy2
import eyetype
import shutil

logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)


def runWithTimeOutByDaemon(cmd, working_dir, timeout_sec, verbose, idn, shell=False):


    outpipe = sys.stdout if verbose else subprocess.PIPE
    errpipe = sys.stderr if verbose else subprocess.PIPE
    try:
        proc = subprocess.Popen(cmd, cwd=working_dir, stdout=outpipe,
                                stderr=errpipe, shell=shell)
    except Exception as e:
        # TODO may clean up
        return idn, -1, "", str(e)


    kill_proc = lambda p: p.kill()
    timer = Timer(timeout_sec, kill_proc, [proc])

    try:
        timer.start()
        stdout, stderr = proc.communicate()


    finally:
        timer.cancel()

    return idn, proc.returncode, stdout, stderr



def 
(workerNum, deamonProcess, argsList, callback=eyetype.noop):
    pool = multiprocessing.Pool(workerNum)
    res = [pool.apply_async(deamonProcess, anarg, callback=callback) for anarg in argsList]
    pool.close()
    pool.join()

    return [r.get() for r in res]


def copytree(src, dst):
    distutils.dir_util.copy_tree(src, dst)





log_level_mapping = {'info': logging.INFO,
                    'warn': logging.WARN,
                    'debug': logging.DEBUG}


def drawProgressBar(percent, suffix, barLen = 50):
    sys.stdout.write("\r")
    progress = ""
    for i in range(barLen):
        if i < int(barLen * percent):
            progress += "="
        else:
            progress += " "
    sys.stdout.write("[ %s ] %.2f%% %s" % (progress, percent * 100, suffix))
    # erase to the end
    sys.stdout.write("\033[K")
    if percent >= 1:
        sys.stdout.write("\n")
    sys.stdout.flush()


def findAllFilePathUnderFolder(dirname, filename):
    res = []
    for filename in glob.iglob(dirname+'/**/'+filename, recursive=True):
        res.append(filename)
    return res


def copySingleFile(src, dst):
    return copy2(src, dst)

parallel_startDeamon