"""
Models for pages.

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

import copy
import os

import arrow

from rookeries import database as db


class Page(db.DatabaseModel):

    # TODO: Break out into content blocks.
    # TODO: Add in content type, created, updated dates and author
    # TODO: Author is based on a user.
    # TODO: Add a language as in markdown / html

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.slug = kwargs.get('slug')
        self.title = kwargs.get('title')
        self.content = kwargs.get('content')
        self.created_at = arrow.ArrowFactory().get(kwargs.get('createdAt'))

    @staticmethod
    def doc_type():
        return 'page'

    def _json_repr(self) -> dict:
        return {
            'slug': self.slug,
            'title': self.title,
            'content': self.content,
            'created': self.created_at.isoformat(),
        }

    def to_api_json(self):
        api_json = copy.deepcopy(self._json_repr())
        # TODO: Add a better way to render based on api endpoints
        api_json['links'] = {'self': f'/api/pages/{self.slug}'}
        return api_json

    def to_db_json(self):
        db_json = copy.deepcopy(self._json_repr())
        return self.attach_db_metadata(db_json)


# TODO: Get rid of demo pages...
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': Page(slug='about', title='About Rookeries',
                  content=read_demo_content('about')),
    'license': Page(slug='license', title='Licence (AGPL)',
                    content=read_demo_content('license')),
    'develop': Page(slug='develop', title='Development',
                    content=read_demo_content('develop')),
}
