"""
Tasks for working with the app.

: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 as rookeries_db
from rookeries.pages import models as page_models
from rookeries.sites import models as site_models
from rookeries.users import models as user_models


@inv.task()
def add_user(ctx, username, password, full_name='Test User'):
    """
    Add user to the application.

    :param ctx: The task context.
    :param username: The username of the user to create.
    :param password: The password for the user to create.
    :param full_name: The full name of the user.
    """
    db_server = rookeries_db.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 = rookeries_db.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_page_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 = {
        'favicon': '/static/images/mr-penguin-amber-favicon.ico',
    }

    def _read_demo_page_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

    def _read_demo_content(filename):
        path_to_file = os.path.join(
            os.path.dirname(__file__), '..', 'tests', 'samples', filename)
        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}'})
    header = _read_demo_content('header.html')
    footer = _read_demo_content('footer.html')

    test_site_ = site_models.Site(
        name='Rookeries',
        menu=menu,
        landing_page='about',
        config=demo_config,
        header=header,
        footer=footer,
    )

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