#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import os
import subprocess
import sys
import docopt

import mus.make

BASE_PATH = os.path.dirname(os.path.realpath(sys.argv[0]))
BASE_PATH = os.path.dirname(BASE_PATH)

def case_make(case_name, remake = False):
    test_file = case_name + '.test.cpp'
    if not os.path.exists(test_file):
        sample_file = case_name + '.sample.cpp'
        code = os.system('ln -s {0} {1}'.format(sample_file, test_file))
        if code != 0:
            exit()

    makefile_content = mus.make.get_make_content(case_name)
    with open('Makefile.mus', 'w') as mf:
        mf.write(makefile_content)

    if remake:
        os.system('make -f Makefile.mus clean')

    code = os.system('make -f Makefile.mus')
    if code != 0:
        exit()



def env_prepare():
    lib_key = 'LD_LIBRARY_PATH'
    if lib_key not in os.environ:
        os.environ[lib_key] = '';
    lib_path = os.environ[lib_key]
    os.environ[lib_key] = '{0}:{1}/lib'.format(lib_path, BASE_PATH)



def case_run(module, n_input):
    if n_input:
        n_input = int(n_input)
        if n_input <= 0:
            print 'Invalid --input: ' + str(n_input)
            exit()
    input_file_path = module + '.input'
    lines = []
    with open(input_file_path) as fin:
        lines = fin.readlines()
    lines.append('\n')

    exe_file = './' + module + '.out'
    inputs = []
    counter = 0
    env_prepare()
    for i in xrange(0, len(lines)):
        if len(lines[i].strip()) == 0:
            counter += 1
            if n_input and n_input > 0 and counter != int(n_input):
                inputs = []
                continue
            print '\n===== [' + str(counter) + '] ====='
            if len(inputs) == 0:
                continue
            p = subprocess.Popen(exe_file, stdin=subprocess.PIPE)
            for line in inputs:
                print line.strip()
                p.stdin.write(line)
            p.stdin.close()
            exit_code = p.wait()
            if exit_code != 0:
                print '[warn] exit code: %d' % (exit_code,)
            inputs = []
        elif lines[i].strip()[0] == '#':
            continue
        else:
            inputs.append(lines[i])


def mustard_main():
    '''mustard main entry
Usage:
    mustard [-m] [-f] [--input=<N>] <case>
    mustard -h | --help
    mustard --version

Options:
    -h --help    Show this screen.
    --version    Show version.
    -m           Run 'make' only, will not run the case
    -f           force re-make
    --input=<N>  Use (N)th input, first is 1.
'''

    arguments = docopt.docopt(mustard_main.__doc__, version="v1.1")

    do_make = arguments['-m']
    re_make = arguments['-f']
    module = arguments['<case>']
    n_input = arguments['--input']

    case_make(module, bool(re_make))

    if do_make:
        return

    case_run(module, n_input)



if __name__ == '__main__':
    mustard_main()
