# coding=utf-8
"""
Tasks for running various tests for Rookeries

:copyright: Copyright 2013-2015, Dorian Pula <dorian.pula@amber-penguin-software.ca>
:license: AGPL v3+
"""

import invoke as inv
from invoke import exceptions as inv_err
import pexpect

from . import utils


@inv.task
def clean():
    """Cleans test reports and artifacts."""
    test_folders = ['cover', '.tox']
    utils.delete_in_path_list(test_folders)


@inv.task
def style():
    """Test the coding style using Flake8."""
    inv.run('flake8', echo=True, pty=True)
    inv.run('npm run lint', echo=True, pty=True)


def _prepare_py_test_command(test_path, check_coverage_on='', verbosity=0, **extra_test_params):
    verbose_flag = ''
    if verbosity > 0:
        verbose_flag = '-{}'.format('v' * verbosity)

    if verbosity >= 3:
        verbose_flag = '{} -r a'.format(verbose_flag)

    coverage_flag = ''
    if check_coverage_on:
        coverage_flag = '--cov {pkg} --cov-report=term-missing --capture=no'.format(pkg=check_coverage_on)
    additional_test_params = ' '.join(
        ['--{}={}'.format(key.replace('_', '-'), value) for (key, value) in extra_test_params.items()])
    return 'py.test {path} {coverage} {verbose} {extra_options}'.format(
        path=test_path, coverage=coverage_flag, verbose=verbose_flag, extra_options=additional_test_params)


@inv.task
def server(couchdb_connection='http://admin:password@localhost:5984/', keep_test_db=False, verbosity=0):
    """
    Test the server webapp using both unit and integration tests.

    :param couchdb_connection: Connection to the CouchDB database to go against.
    :param keep_test_db: Keep the test data and database around.
    :param verbosity: The amount of logging from the test.  Default is 0 and is the lowest.  3 is the highest.
    """

    try:
        with utils.test_database(couchdb_connection=couchdb_connection, keep_test_db=keep_test_db):
            test_command = _prepare_py_test_command('tests/server', check_coverage_on='rookeries', verbosity=verbosity)
            inv.run(test_command, echo=True, pty=True)

    except inv_err.Failure as err:
        print('Server test failed." \n')
        raise err


@inv.task
def tasks(verbosity=0):
    """
    Test the bundled tasks for working with rookeries.

    :param verbosity: The amount of logging from the test.  Default is 0 and is the lowest.  3 is the highest.
    """
    test_command = _prepare_py_test_command('tests/tasks', check_coverage_on='tasks', verbosity=verbosity)
    inv.run(test_command, echo=True, pty=True)


@inv.task
def features(server_host='localhost', port=7000, couchdb_connection='http://admin:password@localhost:5984/',
             keep_test_db=False, verbosity=0, browser='firefox', remote_browser_url=''):
    """
    Test the high-level functionality of rookeries.

    :param server_host: The hostname of the server to test.
    :param port: The port that the server runs on.
    :param couchdb_connection: Connection to the CouchDB database to go against.
    :param keep_test_db: Keep the test data and database around.
    :param verbosity: The amount of logging from the test.  Default is 0 and is the lowest.  3 is the highest.
    :param browser: The web driver to use.  Default firefox, see `pytest-splinter's option for --splinter-webdriver for
        more details`<https://github.com/pytest-dev/pytest-splinter#command-line-options>_
    :param remote_browser_url: The URI to a remote browser. Optional see `pytest-splinter's option for
        --splinter-remote-url for more details`<https://github.com/pytest-dev/pytest-splinter#command-line-options>_
    """

    test_server = None
    try:
        with utils.test_database(couchdb_connection=couchdb_connection, keep_test_db=keep_test_db):
            if server_host in ['localhost', '127.0.0.1']:
                test_server = pexpect.spawn('inv server.run --port {}'.format(port))

            test_command = _prepare_py_test_command(
                'tests/functional', verbosity=verbosity, server_hostname=server_host, server_port=port,
                splinter_webdriver=browser, splinter_remote_url=remote_browser_url,
                splinter_screenshot_dir='features_test_output'
            )
            inv.run(test_command, echo=True, pty=True)

    except inv_err.Failure as err:
        print('Server test failed." \n')
        raise err
    finally:
        if test_server:
            test_server.terminate()


@inv.task
def client():
    inv.run('npm run test', echo=True, pty=True)


@inv.task(clean, server, tasks, client, style, name='all')
def test_all():
    print(u'Everything looks good! ☻')
