import re
import os
import random
import platform
import subprocess

from itest.utils import check_output


CWD = os.path.dirname(os.path.abspath(__file__))

SUDO_PASSWD = os.environ.get('ITEST_SUDO_PASSWD', '123456')
RUN_CASE_TIMEOUT=60*60*3
HANGING_TIMEOUT = 15 * 60 # 15 minutes
TZ = 'Asia/Shanghai'

def sample_files(path, k, predict=None):
    def find_files(top):
        for dirpath, _dirnames, filenames in os.walk(top):
            for name in filenames:
                path = os.path.join(dirpath, name)
                if not predict or predict(path):
                    yield path

    files = list(find_files(path))
    idx = random.sample(range(0, len(files)), min(k, len(files)))
    return [ files[i] for i in idx ]

def is_bootstrap_file(case_path):
    cases = subprocess.Popen('grep native %s' % (case_path), shell=True, stdout=subprocess.PIPE).communicate()[0]
    return cases == ''

def random_tests(predict=None):
    path = os.path.join(CWD, 'cases')
    def squrash(a, b):
        a.extend(b)
        return a
    return reduce(squrash, [ sample_files(os.path.join(path, comp), 2, predict)
        for comp in os.listdir(path) ])


def get_specific_cases(type):
    if type == 'native':
        cmd = "grep 'runtime=native' cases/create/ -rl"
    elif type == 'bootstrap':
        cmd = "grep 'runtime=native' cases/create/ -rL"
    elif type == 'fast':
        cases = [ 'cases/create/func_cases/mic_cr_auto_raw.case',
                  'cases/create/func_cases/mic_cr_auto_loop.case' ]
        for case in cases:
            full_path = os.path.join(CWD, case)
            cases[cases.index(case)] = full_path
        return cases
    proc = subprocess.Popen(cmd,
                            shell=True,
                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = proc.communicate()
    cases = stdout.split()
    for case in cases:
        full_path = os.path.join(CWD, case)
        cases[cases.index(case)] = full_path
    return cases

SUITES = {
    'random': random_tests(),
    'fast': random_tests(is_bootstrap_file),
    #'ref-updated': 'fast',
    #'patchset-created': 'fast',
    'ref-updated': get_specific_cases('fast'),
    'patchset-created': get_specific_cases('fast'),
    'bootstrap': get_specific_cases('bootstrap'),
    'native': get_specific_cases('native')
}
