#!/usr/bin/env python
'An interactive fiction system offering control over the narrative discourse.'

__author__ = 'Nick Montfort'
__copyright__ = 'Copyright 2011 Nick Montfort'
__license__ = 'ISC'
__version__ = '0.5.0.0'
__status__ = 'Development'

import sys
import os
import time
import optparse

import clarifier
import command_map
import discourse_model
import joker
import microplanner
import preparer
import presenter
import recognizer
import reply_planner
import world_model

class Multistream(object):
    'Encapsulates multiple output streams.'

    def __init__(self, streams, log=None):
        self.streams = streams
        self.log = log

    def close(self):
        """Close each of the streams.

        If one or more of the streams returns some exit status, the maximum
        value is returned by this method."""
        overall_status = None
        for stream in self.streams:
            status = stream.close()
            if status is not None:
                overall_status = max(overall_status, status)
        return overall_status

    def write(self, string):
        'Write string to each of the streams.'
        for stream in self.streams:
            stream.write(string)


def start_log(out_streams):
    'Open a log file named with the next available integer.'
    log_files = [os.path.splitext(l)[0] for l in os.listdir('logs/') if
                 os.path.splitext(l)[1] == '.log']
    if len(log_files) == 0:
        latest = 0
    else:
        latest = max([int(log_file) for log_file in log_files])
    log_file = 'logs/' + str(latest + 1) + '.log'
    try:
        log = file(log_file, 'w')