"""
Datastores for handling the retrieval and storage of journal entries.

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

import io
import os

import flask

from rookeries.journal import models


class FileSystemDataStore(object):
    def __init__(self, app_root_path, root_path, extension='md'):
        self.app_root_path = app_root_path
        self.root_path = root_path
        self.file_extension = extension

    def __getitem__(self, item):
        markdown_entry_path = self._build_path_to_resource(item)

        if not os.path.exists(markdown_entry_path):
            raise KeyError("File '{}' for '{}' could not be found".format(markdown_entry_path, item))

        with io.open(markdown_entry_path, mode="r", encoding="utf-8") as markdown_file:
            markdown_content = markdown_file.read()

        return models.JournalEntry(item, content=markdown_content)

    def _build_path_to_resource(self, item):
        resource_file_name = "{}.{}".format(item, self.file_extension)
        return flask.safe_join(self.app_root_path, flask.safe_join(self.root_path, resource_file_name))
