#!/usr/bin/env python
'''
Copyright (C) 2011, Digium, Inc.
Richard Mudgett <rmudgett@digium.com>

This program is free software, distributed under the terms of
the GNU General Public License Version 2.
'''

import sys
import os
import time
from twisted.internet import reactor, defer

sys.path.append("lib/python")
from asterisk.test_case import TestCase

class SIPCallTest(TestCase):
    def __init__(self):
        TestCase.__init__(self)

        self.connected_chan1 = False
        self.connected_chan2 = False
        self.connected_srtp1 = False
        self.connected_srtp2 = False
        self.not_acceptable1 = False

        # Create one AGI server
        # Will call fastagi_connect() once an AGI connection is established.
        self.create_fastagi_factory()

        # Create two Asterisk instances ...
        self.create_asterisk(2)

    # This is called when the reactor has started running.
    def run(self):
        TestCase.run(self)

        # Create one AMI connection (to Ast1)
        # Will call ami_connect() once the AMI connection is established.
        self.create_ami_factory()

    # Once the AMI Factory connects to Asterisk, this function fires.
    def ami_connect(self, ami):
        print "AMI - connected"

        # Register for the AMI event we are interested in.
        self.ami[ami.id].registerEvent("VarSet", self.ami_test_varset)

        print "Initiating test call"
        self.ast[0].cli_originate("SIP/2000/2000 extension 1000@siptest1")

    # This is called whenever an AMI VarSet event occurs on Ast1.
    def ami_test_varset(self, ami, event):
        print "Received VarSet event from AMI"
        #print event
        if not event.has_key("variable") or not event.has_key("value"):
            # These entries should always be in the VarSet event.
            print "Event is missing 'variable' or 'value' entry"
            return
        print "  Value of event[variable] = %s" % (event["variable"])
        print "  Value of event[value] = %s" % (event["value"])
        if event["variable"].startswith("~HASH~SIP_CAUSE~"):
            cause_code = event["value"].split(" ")[1]
            if cause_code == "488":
                # The call failed for the expected reason "488 Not acceptable".
                self.not_acceptable1 = True

                # We are done early
                self.stop_reactor()

    # This is called by each Asterisk instance if the call gets connected.
    def fastagi_connect(self, agi):
        def get_test_result(val):
            print "Connection result '%s'" % val
            if val.split("-")[0] == "SIP/2000":
                # Outgoing call on Ast1
                self.connected_chan1 = True
                if val.split("=")[1] == "1":
                    self.connected_srtp1 = True
            elif val.split("-")[0] == "SIP/1000":
                # Incoming call on Ast2
                self.connected_chan2 = True
                if val.split("=")[1] == "1":
                    self.connected_srtp2 = True
            else:
                print "Don't know which side is connected."

            # Hold the AGI connection until the reactor times out
            # so the other side has a chance to get its test result.
            ## Drop the AGI connection
            #agi.finish()

        agi.getVariable("TEST_RESULT").addCallback(get_test_result)

    def stop_asterisk(self):
        TestCase.stop_asterisk(self)

        # Determine if the test passed
        print "self.connected_chan1:%s" % (self.connected_chan1)
        print "self.connected_srtp1:%s" % (self.connected_srtp1)
        print "self.not_acceptable1:%s" % (self.not_acceptable1)
        print "self.connected_chan2:%s" % (self.connected_chan2)
        print "self.connected_srtp2:%s" % (self.connected_srtp2)
        if not self.connected_chan1 and not self.connected_srtp1 and self.not_acceptable1 and not self.connected_chan2 and not self.connected_srtp2:
            print "Test passed"
            self.passed = True

def main():
    test = SIPCallTest()
    test.start_asterisk()
    reactor.run()
    test.stop_asterisk()
    if test.passed:
        return 0
    return 1

if __name__ == "__main__":
    sys.exit(main() or 0)


# vim:sw=4:ts=4:expandtab:textwidth=79
