#!/usr/bin/python
# -----------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
# -----------------------------------------------------------------------
import os
import sys
import getopt
import json

from ducc_util import DuccUtil

class DuccStateListener(DuccUtil):

    def run(self):
        CMD = self.java() + ' org.apache.uima.ducc.tools.DuccPubListener'
        CMD = CMD + ' -host '  + self.host
        CMD = CMD + ' -port '  + self.port
        CMD = CMD + ' -topic ' + self.topic
        CMD = CMD + ' -output ' + self.output
        if ( self.agent != None ):
            CMD = CMD + ' -agent ' + self.agent
            
        os.system(CMD)

        if ( self.agent != None ):
            self.output = self.output + '.' + self.agent

        fi = open(self.output + '.json')
        fo = open(self.output + '.json.pretty', 'w')
        obj = json.load(fi)
        print "Pretty-printing to", self.output
        json.dump(obj, fo, indent=3)
        fi.close()
        fo.close()
        os.remove(self.output + '.json')
        os.rename(self.output + '.json.pretty', self.output);

    def usage(self, msg):
        if ( msg != None ):
            print msg
        print "Usage:"
        print "   ducc_statedump [options]"
        print "   If no options are given this help screen is shown."
        print ""
        print "Options:"
        print "   -n This is DUCC's ActiveMQ node, defaults to 'localhost'."
        print ""
        print "   -p This is DUCC's ActiveMQ port, defaults to 61616."
        print ""
        print "   -s This is the state to dump.  One of rm sm or pm metrics inventory."
        print ""
        print "   -o This is the name of a tempfile where the state is written, defaults to duccstate.out."
        print ""
        print "   --nocp Inhibit the classpath in the OR state dumps."
        print ""
        print "Remember that you will likely have to wait a few seconds for publications to arrive after starting."
        print ""
        print "To get a pretty-printed version of the xstream outpout."
        print "   xmllint --format duccstate.out --output duccstate.out.pretty"

        sys.exit(0)

    def main(self, argv):

        if ( len(argv) == 0 ):
            self.usage(None)

        self.host = 'localhost'
        self.port = '61616'
        self.output = None
        self.state = 'or'
        self.agent = None

        try:
            opts, args = getopt.getopt(argv, 'n:o:p:s:t:?h')
        except:
            self.usage('Invalid arguments ' + ' '.join(argv))
                       
        for ( o, a ) in opts:
            if o in ( '-n' ): 
                self.host = a
            elif o in ( '-o' ):
                self.output = a
            elif o in ( '-p' ):
                port = int(a)        # quick check to see if it converts
                self.port = a
            elif o in ( '-s' ):
                self.state = a
            elif o in ( '-t' ):
                timeout = int(a)
                self.timeout = a
            elif o in ( '-?', '-h' ):
                self.usage()
                
        CLASSPATH = os.environ['CLASSPATH']
        CLASSPATH = CLASSPATH + ':' + self.DUCC_HOME + '/lib/uima-ducc/examples/*'
        os.environ['CLASSPATH'] = CLASSPATH

        if ( self.state == 'or' ):
            self.topic = 'ducc.orchestrator.state'
        elif (self.state == 'rm' ):
            self.topic = 'ducc.rm.state'
        elif (self.state == 'sm' ):
            self.topic = 'ducc.sm.state'
        elif (self.state == 'pm' ):
            self.topic = 'ducc.pm.state'
        elif (self.state.startswith('inventory') ):
            toks = self.state.split('@')
            if ( len(toks) != 2 ):
                print "Invalid state, must be 'inventory@node'"
                sys.exit(1)
            self.topic = 'ducc.node.inventory'
            self.agent = toks[1]
        elif (self.state.startswith('metrics') ):
            toks = self.state.split('@')
            print 'toks', toks
            if ( len(toks) != 2 ):
                print "Invalid state, must be 'metrics@node'"
                sys.exit(1)
            self.topic = 'ducc.node.metrics'
            self.agent = toks[1]

        if ( self.output == None ):
            of = self.topic 
            if ( self.agent != None ):
                of = of + ".agent"
            self.output = of

        print '-----------------------'
        print 'host', self.host
        print 'port', self.port
        print 'output file', self.output
        print 'topic', self.topic
        if ( self.agent != 'none' ):
            print 'agent', self.agent
        print '-----------------------'

        self.run()

if __name__ == "__main__":
    dsl = DuccStateListener()
    CLASSPATH = os.environ['CLASSPATH'] + ':' + dsl.DUCC_HOME + '/examples/lib/uima-ducc-examples.jar'
    os.environ['CLASSPATH'] = CLASSPATH
    dsl.main(sys.argv[1:])
