"""
Sample database test fixtures for database related tests.

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

import pathlib

from sqlalchemy import orm

from rookeries.sites import models as site_models
from rookeries.pages import models as journal_models


def create_sample_page(page_id, title, content_file):
    sample_content_path = pathlib.Path('docs', content_file)
    with sample_content_path.open(encoding='utf-8') as markdown_file:
        content = markdown_file.read()
    return {'slug': page_id, 'title': title, 'content': content}


def sample_page_collection():
    return [
        create_sample_page('about', title='About Rookeries', content_file='about.md'),
        create_sample_page('develop', title='Develop', content_file='develop.md'),
        create_sample_page('license', title='License (AGPL)', content_file='license.md'),
    ]


def populate_database(db_engine):
    site_config = {
        'name': 'Rookeries',
        'tagline': 'Simple Site Scaffolding!',
        'logo': '/static/images/mr-penguin-amber.svg',
        'footer': 'Rookeries - © 2013-2016 - Amber Penguin Software',
        'favicon': '/static/mr-penguin-amber-favicon.ico',
    }

    second_site_config = {
        k: v if v.startswith("/") else "".join(reversed(v))
        for k, v in site_config.items()
    }

    test_site = site_models.Site(name='Test Site', url='https://test.rookeries.org/', config=site_config,
                                 api_key='b423602c-2156-4eab-b647-f6b05d66c2e3')
    # TODO: Break out the second site into a test harness instead.
    another_site = site_models.Site(name='YASite', url='https://yatest.rookeries.org/', config=second_site_config)

    pages = [journal_models.Page(**page) for page in sample_page_collection()]
    menu_items = [
        site_models.SiteMenu(title=page.title, site=test_site, page=page, orderinal=orderinal)
        for orderinal, page in enumerate(pages)
    ]

    # TODO: Come up with nice bootstrapping setup for Rookeries.
    session = orm.sessionmaker(bind=db_engine, autocommit=True)()
    session.begin()
    session.add(another_site)
    session.add(test_site)
    session.add_all(pages)
    session.add_all(menu_items)
    session.commit()
    session.close()
