/*
    This class demonstrates use of the SimpleCapi.java class 
    for creating a simple java voice-response application
*/

import java.io.*;
import java.net.*;

public class TwoLinesIncomingDemo extends Thread
{
    int num;

    public TwoLinesIncomingDemo(int num) 
    {
	this.num = num;
    }

    protected void printThread(String message)
    {
	System.out.println("[ Thread "+num+" ]  "+message);
    }

    public void run()
    {
	try {
	    SimpleCapi capi=new SimpleCapi("127.0.0.1", 7347);

	    /* set msisdn according to thread */
	    if(num==1) {
		capi.setMSISDN("33");
	    } else {
		capi.setMSISDN("34");
	    }

	    capi.acceptCalls();
	    boolean running = true;
	    String msisdn;
	    while(running)
	    {
		printThread("waiting for call...");
		while(true)
		{
		    CapiEvent event = capi.listen(60);
		    if(event.type == capi.CAPI_EVENT_INCOMING)
		    {
			printThread("trying to answer to "+event.msisdn+"...");
			if(capi.answer(event)) {
			    msisdn = event.msisdn;
			    break;
			}
			else {
			    printThread("Couldn't answer. Waiting for call...");
			}
		    } else {
			printThread("Unexpected Event: "+event);
		    }
		}
		printThread("Connected to "+msisdn+".");
		int jobid = -10;
		if(num==1) {
		    jobid = capi.speak("Be welcome to line 33 of I.V.R.");
		} else {
		    jobid = capi.speak("Be welcome to line 34 of I.V.R.");
		}
		//jobid = capi.play("welcome.wav");
	    
		while(true)
		{
		    CapiEvent event = capi.listen(60);
		    if(event.type == capi.CAPI_EVENT_DONE &&
			event.jobid == jobid) {
			printThread("message done playing.");
		    } else  if (event.type == capi.CAPI_EVENT_HANGUP) {
			printThread("user hung up...");
			break;
		    } else if (event.type == capi.CAPI_EVENT_DIALTONE) {
			printThread("user pressed the butten: " + event.tone);
			capi.stop(jobid);
		    } else {
			printThread("Unexpected Event: "+event);
		    }
		}
		printThread("No longer connected to "+msisdn+".");
	    }
	    capi.close(); 
	}
	catch (Exception e) {
	    e.printStackTrace();
	}
    }

    public static void main(String args[]) throws Exception
    {
	TwoLinesIncomingDemo thread1 = new TwoLinesIncomingDemo(1);
	TwoLinesIncomingDemo thread2 = new TwoLinesIncomingDemo(2);
	thread1.start();
	thread2.start();
    }
}
