#!/usr/bin/python
# Solfege - free ear training software
# Copyright (C) 2007, 2008 Tom Cato Amundsen
# License is GPL, see file COPYING

import unittest
import sys
import os
import shutil
import atexit

# we need this hack because doctest messes with _
def f(s):
    if type(s) == type(""):
        print "'%s'" % s
    elif s is None:
        return
    else:
        print s

sys.displayhook = f

from src import testlib
import src.i18n
src.i18n.setup(".")

import src.lessonfile
src.lessonfile.manager = src.lessonfile.LessonFileManager(False)
import src.statistics
src.statistics.db = src.statistics.DB(None)

import tempfile
import src.lessonfile
src.lessonfile.MusicBaseClass.temp_dir = tempfile.mkdtemp(prefix="solfege-")

import src.cfg
src.cfg.initialise("default.config", None, "")
src.cfg.set_int('config/preferred_instrument', 0)
src.cfg.set_int('config/lowest_instrument', 1)
src.cfg.set_int('config/middle_instrument', 2)
src.cfg.set_int('config/highest_instrument', 3)
src.cfg.set_int('config/lowest_instrument_volume', 121)
src.cfg.set_int('config/middle_instrument_volume', 122)
src.cfg.set_int('config/highest_instrument_volume', 123)
src.cfg.set_bool('config/override_default_instrument', False)
src.cfg.set_bool('testing/may_play_sound', False)

if os.path.exists(testlib.outdir):
    shutil.rmtree(testlib.outdir)
os.mkdir(testlib.outdir)

import soundcard
from src.osutils import *
soundcard.initialise_external_midiplayer(
    src.cfg.get_string("sound/midi_player"))

soundcard.synth.start_testmode()


import mpd.tests
import soundcard.tests
import src.tests
import src.tests.test_cfg

# test_cfg has to be called last because it changes the cfg database.
suite = unittest.TestSuite((
    mpd.tests.suite,
    soundcard.tests.suite,
    src.tests.suite,
    src.tests.test_cfg.suite,
))

class MyProg(unittest.TestProgram):
    USAGE = """\
Usage: %(progName)s [options] [test] [...]

Options:
  -h, --help       Show this message
  -v, --verbose    Verbose output
  -q, --quiet      Minimal output

Examples:
  %(progName)s             - run default set of tests
  %(progName)s substring   - run any tests that contains substring it its
                             name or module name
"""


def iter_suite(suite):
    for t in suite:
        if isinstance(t, unittest.TestSuite):
            for xx in iter_suite(t):
                yield xx
        else:
            yield t

args = [x for x in sys.argv[1:] if x not in ('-v', '-q', '-h')]
if args and '-h' not in sys.argv:
    new_suite = unittest.TestSuite()
    r = unittest.TestResult()
    for test in iter_suite(suite):
        for a in args:
            if a in test.id():
                new_suite.addTest(unittest.defaultTestLoader.loadTestsFromName(test.id()))
    result = unittest.TextTestRunner(verbosity=1 + int('-v' in sys.argv) - int('-q' in sys.argv)).run(new_suite)
    sys.exit(not result.wasSuccessful())


sys.argv.append("suite")

def rmtemp():
    shutil.rmtree(testlib.outdir)

atexit.register(rmtemp)

MyProg()
