#!/usr/bin/env python
#
# Copyright (c) 2013 Matt Behrens <matt@zigg.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.


from octothorpe.ami import AMIProtocol


"""Example to watch events fly by on an Asterisk Manager Interface"""


class AMIWatcher(AMIProtocol):

    def __init__(self, username, secret):
        self.username = username
        self.secret = secret


    def bannerReceived(self, banner):
        AMIProtocol.bannerReceived(self, banner)
        self.loginMD5(self.username, self.secret)


    def eventReceived(self, event, message):
        AMIProtocol.eventReceived(self, event, message)
        print 'Event received:', event
        for key in sorted(message.keys()):
            print '\t%r: %r' % (key, message[key])


if __name__ == '__main__':
    from twisted.internet import reactor
    from twisted.internet.protocol import ClientFactory
    from twisted.python import log
    from sys import stderr

    class AMIWatcherFactory(ClientFactory):
        def buildProtocol(self, addr):
            return AMIWatcher('manager', 'secret')

    log.startLogging(stderr)
    reactor.connectTCP('172.20.64.100', 5038, AMIWatcherFactory())
    reactor.run()


# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
