from __future__ import print_function
import os, sys, subprocess
from glob import glob
from cStringIO import StringIO

_dotnetConfiguration = "Release"
_dotnetFramework = "netcoreapp1.1"
_dotnetRuntime = "portable"

def execute(args):
    popen = subprocess.Popen(args, stdout=subprocess.PIPE, universal_newlines=True)
    for stdout_line in iter(popen.stdout.readline, ""):
        yield stdout_line 
    popen.stdout.close()
    return_code = popen.wait()
    if return_code:
        raise Exception('Command failed with status %d: %s' % (return_code, ' '.join(args)))

def executePrint(args):
    for line in execute(args):
        print(line, end=' ')

def build(solutionPath):
    if not os.path.exists(solutionPath):
        raise Exception('Solution path not found: %s' % solutionPath)

    executePrint([
        'dotnet', 'clean',
        '--framework', _dotnetFramework, 
        '--configuration', _dotnetConfiguration,
        '--verbosity', 'normal',
        solutionPath
    ])   
    executePrint(['dotnet', 'restore', '--verbosity', 'normal', solutionPath])  
    executePrint([
        'dotnet', 'build',
        '--framework', _dotnetFramework, 
        '--configuration', _dotnetConfiguration,
        '--verbosity', 'normal',
        solutionPath
    ])

def publish(projectPath, outputPath):
    if not os.path.exists(projectPath):
        raise Exception('Project path not found: %s' % projectPath)

    executePrint([
        'dotnet', 'publish',          
        '--framework', _dotnetFramework, 
        '--configuration', _dotnetConfiguration, 
        '--output', outputPath,             
        '--verbosity', 'normal',   
        projectPath
    ])

def runTests(sourcePath, test_filter):
    for projectPath in [y for x in os.walk(sourcePath) for y in glob(os.path.join(x[0], test_filter))]:
        outputPath = os.path.join(os.path.dirname(projectPath), 'bin', _dotnetConfiguration, _dotnetFramework)
        executePrint([
            'dotnet', 'test', 
            '--no-build',             
            '--framework', _dotnetFramework, 
            '--configuration', _dotnetConfiguration, 
            '--output', outputPath,             
            '--verbosity', 'normal', 
            projectPath
        ])