#!/usr/bin/env python
'''
Copyright (C) 2012, Digium, Inc.
Kinsey Moore <kmoore@digium.com>

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

import sys
import logging

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

logger = logging.getLogger(__name__)

class AnsweredElsewhereTest(TestCase):
    def __init__(self):
        self.event_count = 0
        self.expected_events = 6
        self.ans_elsewhere_count = 0
        self.expected_ans_elsewhere = 2
        TestCase.__init__(self)
        self.create_asterisk()

    def ami_connect(self, ami):
        logger.info("Initiating call to local/100@test on Echo() for answered_elsewhere test")

        ami.registerEvent('Hangup', self.__hangup_cb)
        ami.originate("local/100@test", application="Echo").addErrback(self.handle_originate_failure)

    def __hangup_cb(self, ami, event):
        logger.info("Got hangup event")
        self.event_count += 1
        if event['cause'] == '26':
            self.ans_elsewhere_count += 1

        if self.event_count == self.expected_events:
            if self.ans_elsewhere_count == self.expected_ans_elsewhere:
                self.passed = True
            else:
                logger.error("Test failed with %d received events and %d "\
                    "events with the answered_elsewhere cause code" %
                    (self.event_count, self.ans_elsewhere_count))
            self.stop_reactor()

    def run(self):
        TestCase.run(self)
        self.create_ami_factory()

def main():
    test = AnsweredElsewhereTest()
    reactor.run()

    if not test.passed:
        return 1

    return 0

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

