#!/usr/bin/env python
'''
Copyright (C) 2013, 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 os
import logging
import shutil

from twisted.internet import reactor

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

LOGGER = logging.getLogger(__name__)

class FaxLocalQueryOptionTest(TestCase):
    '''This class sets up and manages the Local channel fax queryoptions
    passthrough test.'''

    def __init__(self):
        '''Initialize the class and copy the tiff to an accessible place.'''
        TestCase.__init__(self)
        self.reactor_timeout = 120


        self.connections_established = 0
        self.success_received = 0
        self.create_asterisk(count=2)

        # copy the tiff file we are going to send to a good known location
        tiff_path = os.path.dirname(os.path.realpath(__file__))
        shutil.copy("%s/send.tiff" % (tiff_path), "/tmp")

    def ami_connect(self, ami):
        '''Setup AMI listeners and start the test.'''
        self.connections_established += 1

        ami.registerEvent('UserEvent', self.fax_result)

        if self.connections_established != 2:
            return

        LOGGER.info("Originating fax call")
        self.ami[0].originate(
            channel="sip/1234@fax",
            exten="1234",
            context="local-sendfax",
            priority=1
        ).addErrback(self.handle_originate_failure)

    def run(self):
        '''Setup debugging on the asterisk instances and create AMI
        connections.'''
        TestCase.run(self)
        self.ast[0].cli_exec("sip set debug on")
        self.ast[0].cli_exec("fax set debug on")
        self.ast[0].cli_exec("udptl set debug on")
        self.ast[1].cli_exec("sip set debug on")
        self.ast[1].cli_exec("fax set debug on")
        self.ast[1].cli_exec("udptl set debug on")
        self.create_ami_factory(2)

    def fax_result(self, ami, event):
        '''Handle receipt of user-defined events, looking for indications of
        success or failure.'''
        if event['userevent'] != 'FaxStatus':
            return

        if event['status'] != 'SUCCESS':
            LOGGER.error("Received a FaxStatus event that indicated failure")
            self.stop_reactor()
            return

        self.success_received += 1

        if self.success_received == 2:
            self.passed = True
            self.stop_reactor()

def main():
    '''Run the fax queryoption test.'''
    test = FaxLocalQueryOptionTest()
    reactor.run()
    if test.passed != True:
        if test.connections_established != 2:
            LOGGER.error("Established %d AMI connections instead of 2"
                % test.connections_established)
        if test.success_received != 2:
            LOGGER.error("Received %d success events instead of 2"
                % test.success_received)
        return 1
    return 0

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

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