#!/usr/bin/python
#
# Copyright (C) LoomCM Inc. 2010 for ChronicDB
#
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import logging
import os
import sys
import chronicdb.UserSubmit
    
class CommandLine:
    
    def discover(self):
        user_daemon_server = "api.chronicdb.com"
        user_daemon_port = 2624

        user_submit = chronicdb.UserSubmit.UserSubmit(user_daemon_server, str(user_daemon_port))
        try:
            user_submit.connect()
            user_submit.communicate(sys.argv)
            user_submit.close()                
        except Exception, e:
            sys.stderr.write("Unable to complete ChronicDB request.\n")
            self.logger.debug("Error was: " + str(e))            

    def init_logging(self):
        logging_level = logging.INFO
        if 'CHD_DEBUG' in os.environ.keys() and os.environ['CHD_DEBUG'] == str(1):
            logging_level = logging.DEBUG
        self.logger = logging.getLogger("")
        self.logger.setLevel(logging_level)
        logging_handler = logging.StreamHandler()
        self.logger.addHandler(logging_handler)
        formatter = logging.Formatter('%(asctime)s %(levelname)s:%(name)s:%(message)s', '%Y-%m-%d %H:%M:%S')
        logging_handler.setFormatter(formatter)
        self.logger = logging.getLogger("ChronicDB.CommandLine")

    def go(self):
        self.init_logging()
        self.discover()
        
command_line = CommandLine()
command_line.go()
