# -*- coding: utf-8 -*-
"""A module for writing, reading, and searching files for persistance of brags.
    Implements the three public methods necessary for the bragly.persist API:
        write : saves a message.
        read : reads all messages in the relevant timeframe.
        search: searches all messages according to a number of criteria

Attributes:
    MESSAGE_STR_TEMPLATE (str): A template string for the 'log' format.

"""

from __future__ import absolute_import, print_function
import os
import json
import re
from collections import namedtuple
import arrow

MESSAGE_STR_TEMPLATE = "[{timestamp}][{tags}] {message}\n"


def write(message, file_path=None, file_dir=None, form='json'):
    """Writes a message to a file in the given format.

    Args:
        message (dict): A message, it's timestamp, and any associated tags.
        form (str): A message format, one of log, json, json-pretty
        file_path (str): The file path for the source file. If None, the
            file_path will be generated from the file_dir and the form
        file_dir (str): The file directory for the source file. If None,
            the file_path will be used

    Returns:
        str: On success returns the word "success"
    """
    timestamp = message['timestamp'].isoformat()
    tags = message['tags']
    message = message['message']

    if form == 'json':
        message_str = "{}\n".format(json.dumps(
            dict(
                message=message,
                tags=tags,
                timestamp=timestamp
            ),
        ))
    elif form == 'json-pretty':
        message_str = "{}\n".format(json.dumps(
            dict(
                message=message,
                tags=tags,
                timestamp=timestamp
            ),
            indent=2