#!/usr/bin/env python
# encoding: utf-8
"""
resync-simulator: The ResourceSync command line tool for simulating a changing
Web data source.

Created by Bernhard Haslhofer on 2012-04-24.
Includes contributions by Simeon Warner
Copyright 2012-2013, ResourceSync.org. All rights reserved.
"""

import sys
import optparse
import yaml
import logging
import logging.config

from simulator.source import Source
from simulator.http import HTTPInterface

DEFAULT_CONFIG_FILE = 'config/default.yaml'
DEFAULT_LOG_FILE = 'config/logging.yaml'


def main():

    # Define simulator options
    parser = optparse.OptionParser(description="ResourceSync Source Simulator")
    parser.add_option('--config-file', '-c',
                      default=DEFAULT_CONFIG_FILE,
                      help="the simulation configuration file")
    parser.add_option('--log-config', '-l',
                      default=DEFAULT_LOG_FILE,
                      help="the logging configuration file")
    parser.add_option('--port', '-p', type=int,
                      default=8888,
                      help="the HTTP interface port that the server will run on")
    parser.add_option('--base-uri', '-b',
                      default='',
                      help="the base URI where the simulator is running (defaults to localhost:port)")

    # Parse command line arguments
    (args, clargs) = parser.parse_args()

    # Load the logging configuration file and set up logging
    if sys.version_info >= (2, 7):
        # this stuff requires 2.7
        logconfig = yaml.load(file(args.log_config, 'r'))
        logging.config.dictConfig(logconfig)
    else:
        #FIXME - how ton configure for 2.6?
        pass

    # Load the YAML configuration file
    config = yaml.load(file(args.config_file, 'r'))

    # Set up the source
    source_settings = config['source']
    base_uri = args.base_uri
    if (base_uri == ''):
        base_uri = 'http://localhost:' + str(args.port)
    source = Source(source_settings, base_uri, args.port)

    # Set up and register the source resource_list (if defined)
    if 'resource_list_builder' in config:
        klass_name = config['resource_list_builder']['class']
        mod = __import__('simulator.source', fromlist=[klass_name])
        resource_list_builder_klass = getattr(mod, klass_name)
        builder = resource_list_builder_klass(source, config['resource_list_builder'])
        source.add_resource_list_builder(builder)

    # Set up and register change memory (if defined)
    if 'changememory' in config:
        klass_name = config['changememory']['class']
        mod = __import__('simulator.changememory', fromlist=[klass_name])
        changemem_klass = getattr(mod, klass_name)
        changememory = changemem_klass(source, config['changememory'])
        source.add_changememory(changememory)

    # Bootstrap the source
    source.bootstrap()

    # Start the Web interface, run the simulation
    # Attach HTTP interface to source
    http_interface = HTTPInterface(source)
    try:
        http_interface.start()
        source.simulate_changes()
    except KeyboardInterrupt:
        print "Exiting gracefully..."
    finally:
        http_interface.stop()

if __name__ == '__main__':
    main()
