"""
Tasks for working with a Docker Compose setup for testing and development.

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


import invoke as inv
import pycouchdb

from . import utils


@inv.task
def start_deps():
    """Start the Docker dependencies."""
    inv.run('docker-compose start couchdb', echo=True, pty=True)


@inv.task
def stop_deps():
    """Stop the Docker dependencies."""
    inv.run('docker-compose stop couchdb', echo=True, pty=True)


@inv.task(start_deps)
def bootstrap(couchdb_connection='http://admin:password@localhost:5984/', db_name='rookeries', reset_db=False):
    """Start the Docker dependencies."""
    couchdb_server = pycouchdb.Server(couchdb_connection)
    try:
        sample_db = couchdb_server.database(db_name)
    except pycouchdb.exceptions.NotFound:
        sample_db = None

    if not reset_db and sample_db is not None:
        return

    if reset_db and sample_db is not None:
        couchdb_server.delete(db_name)

    with utils.test_database(couchdb_connection=couchdb_connection, keep_test_db=True, test_db_name=db_name):
        pass
