#!/usr/bin/env python
import argparse
import logging
import os.path

from opentc.util import setup_logging, setup_config

from opentc.core.server import Server

if __name__ == "__main__":
    config_directories = [os.curdir, os.path.expanduser("~/.opentc"), "/etc/opentc", os.environ.get("OPENTC_CONF_DIR")]
    parser = argparse.ArgumentParser()
    parser.add_argument("-a", "--address", help="define the address for the server")
    parser.add_argument("-C", "--configuration_file", help="set the configuration file")
    parser.add_argument("-l", "--log_configuration_file", help="set the log configuration file")
    parser.add_argument("-p", "--port", help="define the port number which the server uses to listen")
    parser.add_argument("-t", "--timeout", type=float, help="define the time out")
    args = parser.parse_args()

    setup_logging(config_directories=config_directories, config_file=args.log_configuration_file)
    logger = logging.getLogger(__name__)
    cfg = setup_config(config_directories=config_directories, config_file=args.configuration_file)

    tcs = Server(cfg=cfg["server"])
    try:
        logger.info("Server start")
        tcs.start(address=args.address, port=args.port, timeout=args.timeout)
    except KeyboardInterrupt as err:
        logger.info("Server quit")
