#!/usr/bin/env python
#
# Copyright (c) 2013, 2014 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, Channel


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


class WatchedChannel(Channel):
    def variableSet(self, variable, value):
        print 'channel %r set %r=%r' % (self.name, variable, value)
        print '\t(variables=%r)' % (self.variables,)


    def hungUp(self, cause, causeText):
        print 'channel %r hangup (%r: %r)' % (self.name, cause, causeText)


    def renamed(self, oldName, newName):
        print 'renamed %r to %r' % (oldName, newName)


    def extensionEntered(self, *args):
        print 'extension entered: (%d) %r' % (len(self.extensions), args)


class ChannelWatcher(AMIProtocol):
    channelClass = WatchedChannel

    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 newChannel(self, name, channel):
        print 'new channel %r (params=%r)' % (name, channel.params)


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

    class ChannelWatcherFactory(ClientFactory):
        def buildProtocol(self, addr):
            return ChannelWatcher('manager', 'secret')

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


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