#!/usr/bin/env python
'''
Copyright (C) 2010-2014, Digium, Inc.
Erin Spiceland <espiceland@digium.com>
Matt Jordan <mjordan@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
from starpy import fastagi

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

testdir = "tests/fastagi"

LOGGER = logging.getLogger(__name__)

class FastAGISayPhoneticTest(TestCase):
    def __init__(self):
        super(FastAGISayPhoneticTest, self).__init__()
        self.passed = False
        self.notified = False
        self.timeout = 30

        # Listen for results from dialplan
        self.agi_factory = fastagi.FastAGIFactory(self.do_test)
        reactor.listenTCP(4573, self.agi_factory, self.timeout, '127.0.0.1')
        self.agi = None

        # Listen for success or failure of talkdetect
        self.agi_factory2 = fastagi.FastAGIFactory(self.listen_result)
        reactor.listenTCP(4574, self.agi_factory2, self.timeout, '127.0.0.1')
        self.agi2 = None

        self.create_asterisk(base_configs_path="%s/configs" % testdir)

    def listen_result(self, agi):
        LOGGER.info("Got test success confirmation from dialplan.")
        self.agi2 = agi
        self.notified = True

    def on_failure(self, reason):
        LOGGER.error('SAY PHONETIC failed: %s' % reason.getTraceback())
        self.passed = False

    def finish_test(self, result):
        LOGGER.info("AGI command reports success.")
        self.passed = True
        self.read_result()

    # This gets invoked by the dialplan when the call is answered
    # send SAY PHONETIC command and wait for results
    def do_test(self, agi):
        self.agi = agi
        LOGGER.debug("Connection established.")
        return agi.sayPhonetic("cat").addCallback(
            self.finish_test).addErrback(self.on_failure)

    def read_result(self):
        self.agi.finish()
        if self.passed is True and self.notified is True:
            self.agi2.finish()
            LOGGER.info("Test passed")
        else:
            LOGGER.error("Test failed")
        self.stop_reactor()

    def launch_test(self):
        LOGGER.debug("Originating call to begin test.")
        self.ast[0].cli_originate("Local/516@agitest extension 1@td_and_agi_notify")

    def run(self):
        super(FastAGISayPhoneticTest, self).run()
        self.launch_test()


def main():
    test = FastAGISayPhoneticTest()
    reactor.run()
    if test.passed is not True or test.notified is not True:
        return 1

    return 0

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