#!/usr/bin/env python
# vim: sw=3 et:
'''
Copyright (C) 2012, 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 logging

from twisted.internet import reactor

sys.path.append("lib/python")

from asterisk.sipp import SIPpScenario
from asterisk.test_case import TestCase

"""
The TestCase class will initialize the python logger - creating a
logger here will log under the '__main__' namespace
"""
logger = logging.getLogger(__name__)

TEST_DIR = os.path.dirname(os.path.realpath(__file__))

class AMIActionMessageSend(TestCase):
    """
    Test handling of AMI MessageSend action sending SIP MESSAGE
    """
    def __init__(self):
        super(AMIActionMessageSend, self).__init__()
        self.create_asterisk()
        sipp_scenario = { 'scenario':'message_recv.xml', '-p':'5062' }
        self.scenario = SIPpScenario(TEST_DIR, sipp_scenario)

    def run(self):
        super(AMIActionMessageSend, self).run()
        self.create_ami_factory()

    def ami_connect(self, ami):
        """
        This method is called by the StarPY manager class when AMI connects to Asterisk

        Keyword Arguments:
        ami    -    The StarPY manager object that connected
        """
        def __check_result(result):
            self.passed = result.passed
            self.stop_reactor()

        # There is a race between starting SIPp and sending the SIP MESSAGE
        # being sent by MessageSend.  Fortunately, we don't care because SIP
        # will retransmit the MESSAGE so SIPp can catch it on the next go
        # round.
        logger.debug("Starting SIP scenario")
        deferred = self.scenario.run()
        deferred.addCallback(__check_result)

        logger.debug("Sending AMI action MessageSend")
        ami_action = { "Action":"MessageSend", "To":"pjsip:user1", "From":"sip:user", "Body":"Watson, come here." }
        ami.sendDeferred(ami_action).addCallback(ami.errorUnlessResponse)

def main():
    """
    Main entry point for the test.
    """

    test = AMIActionMessageSend()
    reactor.run()

    if not test.passed:
        return 1

    return 0

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