"""
Tasks for working with the database attached to the API.

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

import invoke as inv

from rookeries import database


def _create_db(db, database_name, description):
    print(f'Creating {description} database...')

    if db.exists_db(database_name):
        database.OpStatus.SKIP.print()
        return

    success = db.create_db(database_name)
    status = database.OpStatus.OK if success else database.OpStatus.FAILED
    status.print()


@inv.task()
def init(ctx):
    db = database.CouchDB.configure_from_env()
    print(f'Initializing CouchDB for Rookeries on ${db.server_url()}...')

    _create_db(db, '_users', 'system users')
    _create_db(db, '_replicator', 'replication')
    _create_db(db, '_global_changes', 'change feed')


@inv.task()
def sample_site(ctx):
    pass


@inv.task()
def wait(ctx, timeout=30):
    db = database.CouchDB.configure_from_env()
    ctx.run(f'dockerize -wait {db.server_url()}/ -timeout {timeout}s')
