# Path: botfriend/bot.py
# class Publisher(object):
# 
#     """A way of publishing the output of a bot."""
# 
#     @classmethod
#     def from_config(cls, bot, module, full_config):
#         publish_config = full_config.get('publish', {})
#         module_config = publish_config.get(module)
#         
#         # Try both publish.foo and publish._foo, in case the module
#         # needs to import a package called 'foo' from elsewhere (see
#         # _mastodon.py for an example.)
#         publisher_module = None
#         names = ('botfriend.publish.' + module, 'botfriend.publish._' + module)
#         errors = []
#         for module_name in names:
#             try:
#                 publisher_module = importlib.import_module(module_name)
#                 break
#             except ImportError as e:
#                 errors.append(e)
#         if not publisher_module:
#             raise ImportError(
#                 "Could not import publisher for %s; tried %s. Errors were: %r" % (
#                     module, ", ".join(names), errors
#                 )
#             )
#         publisher_class = getattr(publisher_module, "Publisher", None)
#         if not publisher_class:
#             raise Exception(
#                 "Loaded module %s but could not find a class called Publisher inside." % bot_module
#             )
#         try:
#             publisher = publisher_class(bot, full_config, module_config)
#         except Exception as e:
#             raise Exception(
#                 "Could not import %s publisher for %s: %s" % (
#                     module_name, bot.name, str(e)
#                 )
#             )
#         publisher.service = module
#         return publisher
#     
#     def __init__(self, service_name, bot, full_config, **config):
#         self.service_name=service_name
#         self.bot = bot
# 
#     def attachment_path(self, path):
#         """Convert a path relative to the botfriend root to an absolute
#         path."""
#         d = os.path.split(__file__)[0]
#         return os.path.join(d, path)
#         
#     def publish(self, post, publication):
#         """Publish the content of the given Post object.
# 
#         This probably includes text but may also include binary
#         objects.
# 
#         :param post: A Post object.
#         :param previous_attempt: A Publication object describing the
#            attempt to publish this post. It may have data left in it
#            from a previous publication attempt.
#         """
#         raise NotImplementedError()
# 
# Path: botfriend/model.py
# def _now():
#     """The current time.
# 
#     I've moved this into a function so I can test out whether
#     local time or UTC is better for this purpose.
#     """
#     #return datetime.datetime.now()
#     return datetime.datetime.utcnow()


import os
from nose.tools import set_trace
from botfriend.bot import Publisher
from botfriend.model import _now
"""A publisher that just writes output to a file.

By itself, this is mainly used for testing, but it's also the basis for
classes like PodcastPublisher.
"""

class FileOutputPublisher(Publisher):
    def __init__(
            self, bot, full_config, module_config
    ):
        filename = module_config['filename']
        if not filename.startswith(os.path.sep):
            filename = os.path.join(bot.directory, filename)
        self.path = filename
        dir, ignore = os.path.split(self.path)
        if not os.path.exists(dir):
            os.makedirs(dir)

    def self_test(self):
        dir, ignore = os.path.split(self.path)
        if not os.path.exists(dir):
            raise IOError("Destination directory %s does not exist." % dir)
            
    def publish(self, post, publication):

# Path: botfriend/bot.py
# class Publisher(object):
# 
#     """A way of publishing the output of a bot."""
# 
#     @classmethod
#     def from_config(cls, bot, module, full_config):
#         publish_config = full_config.get('publish', {})
#         module_config = publish_config.get(module)
#         
#         # Try both publish.foo and publish._foo, in case the module
#         # needs to import a package called 'foo' from elsewhere (see
#         # _mastodon.py for an example.)
#         publisher_module = None
#         names = ('botfriend.publish.' + module, 'botfriend.publish._' + module)
#         errors = []
#         for module_name in names:
#             try:
#                 publisher_module = importlib.import_module(module_name)
#                 break
#             except ImportError as e:
#                 errors.append(e)
#         if not publisher_module:
#             raise ImportError(
#                 "Could not import publisher for %s; tried %s. Errors were: %r" % (
#                     module, ", ".join(names), errors
#                 )
#             )
#         publisher_class = getattr(publisher_module, "Publisher", None)
#         if not publisher_class:
#             raise Exception(
#                 "Loaded module %s but could not find a class called Publisher inside." % bot_module
#             )
#         try:
#             publisher = publisher_class(bot, full_config, module_config)
#         except Exception as e:
#             raise Exception(
#                 "Could not import %s publisher for %s: %s" % (
#                     module_name, bot.name, str(e)
#                 )
#             )
#         publisher.service = module
#         return publisher
#     
#     def __init__(self, service_name, bot, full_config, **config):
#         self.service_name=service_name
#         self.bot = bot
# 
#     def attachment_path(self, path):
#         """Convert a path relative to the botfriend root to an absolute
#         path."""
#         d = os.path.split(__file__)[0]
#         return os.path.join(d, path)
#         
#     def publish(self, post, publication):
#         """Publish the content of the given Post object.
# 
#         This probably includes text but may also include binary
#         objects.
# 
#         :param post: A Post object.
#         :param previous_attempt: A Publication object describing the
#            attempt to publish this post. It may have data left in it
#            from a previous publication attempt.
#         """
#         raise NotImplementedError()
# 
# Path: botfriend/model.py
# def _now():
#     """The current time.
# 
#     I've moved this into a function so I can test out whether
#     local time or UTC is better for this purpose.
#     """
#     #return datetime.datetime.now()
#     return datetime.datetime.utcnow()


# Path: botfriend/publish/file.py
import os
from nose.tools import set_trace
from botfriend.bot import Publisher
from botfriend.model import _now

"""A publisher that just writes output to a file.

By itself, this is mainly used for testing, but it's also the basis for
classes like PodcastPublisher.
"""

class FileOutputPublisher(Publisher):
    def __init__(
            self, bot, full_config, module_config
    ):
        filename = module_config['filename']
        if not filename.startswith(os.path.sep):
            filename = os.path.join(bot.directory, filename)
        self.path = filename
        dir, ignore = os.path.split(self.path)
        if not os.path.exists(dir):
            os.makedirs(dir)

    def self_test(self):
        dir, ignore = os.path.split(self.path)
        if not os.path.exists(dir):
            raise IOError("Destination directory %s does not exist." % dir)
            
    def publish(self, post, publication):

        publish_at = post.publish_at or _now()