#!/usr/bin/env python
# vim: sw=3 et:
'''
Copyright (C) 2011, Digium, Inc.
Matthew Nicholson <mnicholson@digium.com>

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

import sys
import os
import re
import shutil

from twisted.internet import reactor

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

class GatewayTest(TestCase):
   event_count = 0
   success_count = 0

   def __init__(self):
      TestCase.__init__(self)
      self.reactor_timeout = 360      
      self.create_asterisk(2)

      # copy the tiff file we are going to send to a good known location
      shutil.copy("%s/send.tiff" % (os.path.dirname(os.path.realpath(__file__)),), "%s%s" % (self.ast[0].base, self.ast[0].directories['astdatadir']))

   def ami_connect(self, ami):
      if ami.id == 0:

         print "sending a call from ast1 to ast2"

         ami.registerEvent('UserEvent', self.fax_result)
         df = ami.originate("sip/ast2-t38/1234", "sendfax", "1234", 1)

         def handle_failure(reason):
            print "error sending originate:"
            print reason.getTraceback()
            self.stop_reactor()

            return reason

         df.addErrback(handle_failure)
      else:
         ami.registerEvent('UserEvent', self.fax_result)

   def fax_result(self, ami, event):
      if event['userevent'] != 'TestStatus' and event['userevent'] != 'FaxStatus':
         return

      self.event_count += 1

      if event['status'] == "SUCCESS":
         self.success_count += 1
      else:
         print "test error, expected SUCCESS"
         print "status: %s" % (event['status'],)
         print "error: %s" % (event['error'],)
         print "statusstr: %s" % (event['statusstr'],)

      self.are_we_there_yet()

   def are_we_there_yet(self):
      if self.event_count == 3:
         if self.success_count == 3:
            self.passed = True
         self.stop_reactor()

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


def main():
   test = GatewayTest()
   test.start_asterisk()
   reactor.run()
   test.stop_asterisk()

   if not test.passed:
      return 1

   return 0

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

