#!/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
import logging
import signal
import subprocess
import time

from twisted.internet import reactor

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

logger = logging.getLogger(__name__)
WORKING_DIR = os.path.abspath(os.path.dirname(__file__))
TEST_DIR = os.path.dirname(os.path.realpath(__file__))

class VoxFaxG711(TestCase):

   def __init__(self):
      TestCase.__init__(self)
      self.reactor_timeout = 180
      self.calling_asterisk = None
      self.receiving_asterisk = None
      self.calling_asterisk_booted = 0
      self.receiving_asterisk_booted = 0
      self.passed = 1
      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[1].base, self.ast[1].directories['astdatadir']))

   def ami_connect(self, ami):
      if ami.id == 0:
         print "Asterisk 1 fully started"
	 self.receiving_asterisk = ami
	 self.receiving_asterisk_booted = 1

      if ami.id == 1:
         print "Asterisk 2 fully started"
	 self.calling_asterisk = ami
	 self.calling_asterisk_booted = 1

      if (self.calling_asterisk_booted == 1 and self.receiving_asterisk_booted == 1):
     	 #Both the asterisk have booted, setup the call
	 time.sleep(20)
         self.calling_asterisk.registerEvent('UserEvent', self.fax_result)
         print "Sending a call from ast2 to ast1"
	 carrier_channel_variables = {'SIPADDHEADER51':'X-VCC-UUID:XE6RL7GAXFHIBHBECK7G5PZ6AM', 'SIPADDHEADER52':'X-VCC-Provider:61 127.0.0.2 BEL','SIPADDHEADER53':'X-VCC-CallType:voxfax',
			 'ASTDATADIR':self.ast[1].base+self.ast[1].directories['astdatadir'],'LOCALSTATIONID':'VoxFaxTester'} 
	 df = self.calling_asterisk.originate(channel = "sip/ast1-g711/1234", context = "sendfax", exten = "1234", priority = "1",variable = carrier_channel_variables)

         def handle_failure(reason):
            print "Failed to send originate"
            print reason.getTraceback()
            self.stop_reactor()

            return reason

         df.addErrback(handle_failure)

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

      logger.info ("Status Received %s"% event['status'])
      logger.info ("Status String Received %s"% event['statusstr'])
      logger.info ("Error Received %s"% event['error'])

      if event['statusstr'] != "OK":
      	    self.passed = 0

      self.stop_reactor()
      	   

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


def main():
    test = VoxFaxG711()

    vcc_log_file = WORKING_DIR + "/vcc_logs.txt"
    #Delete the file vcc_logs.txt
    subprocess.call(["rm","-f",vcc_log_file])

    #Run the agi_load_balance_emulator, last argument specifies that T38 is enabled for thi
    #call
    agiLoadBalancer = subprocess.Popen(["perl","utils/agi_load_balance_emulator.pl","1"])

    #Run the vcc_emulator
    vcc_emulator = subprocess.Popen(["perl", "utils/vcc_emulator.pl", vcc_log_file,"sbc"])

    time.sleep(10) #Wait 10 seconds to ensure that all the sockets are open before running the test	

    test.start_asterisk()
    reactor.run()
    test.stop_asterisk()

    #Kill the AGI LOAD BALANCER
    agiLoadBalancer.send_signal(signal.SIGINT)	

    #Check if VCC EMULATOR IS STILL RUNNING,
    #It can exit in case of failure
    vcc_emulator.poll()
    if (vcc_emulator.returncode == None): 
    	vcc_emulator.send_signal(signal.SIGINT)	
    else:
    	logger.debug("VCC emulator exited during the test...failing the test")
	test.passed = 0

    if not test.passed:
       return 1

    return 0

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

