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

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

import os

import invoke as inv

from rookeries import database
from rookeries.pages import models as page_models
from rookeries.sites import models as site_models
from rookeries.users import models as user_models


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 add_user(ctx, username, password, full_name='Test User'):
    db_server = database.CouchDB.configure_from_env()
    user = user_models.User(
        username=username,
        password=password,
        fullName=full_name,
        profile={
            'email': f'{username}@rookeries.org'
        }
    )
    db_server.create_or_update_document(doc=user.to_db_json())


@inv.task()
def init_demo_site(ctx):
    """Setup a demo site."""
    db_server = database.CouchDB.configure_from_env()
    if not db_server.exists_db(db_server.database):
        db_server.create_db(db_server.database)

    def _generate_page(slug_, title_):
        # TODO: Should check if page exists first.
        content = _read_demo_content(slug_)
        demo_page = page_models.Page(
            slug=slug_,
            title=title_,
            content=content
        )
        db_server.create_or_update_document(doc=demo_page.to_db_json())
        return page_models.Page.find_in_db(db_server, {'slug': slug_})

    demo_config = {
        'tagline': 'Simple Site Scaffolding',
        'favicon': '/static/images/mr-penguin-amber-favicon.ico',
        'logo': '/static/images/mr-penguin-amber.svg',
        'footer': 'Rookeries\n©2013-2017 - Amber Penguin Software'
    }

    def _read_demo_content(page):
        path_to_file = os.path.join(
            os.path.dirname(__file__), '..', 'docs', f'{page}.md')
        with open(path_to_file, 'r') as demo_file:
            file_content = ''.join(demo_file.readlines())

        return file_content

    demo_pages = [
        ('about', 'About Rookeries'),
        ('license', 'Licence (AGPL)'),
        ('develop', 'Development'),
    ]

    menu = []
    for slug, title in demo_pages:
        _generate_page(slug, title)
        menu.append({'title': title, 'url': f'/{slug}'})

    test_site_ = site_models.Site(
        name='Test Site',
        menu=menu,
        landing_page='about',
        config=demo_config
    )

    # TODO: Make a whole lot more robust
    db_server.create_or_update_document(doc=test_site_.to_db_json())


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