/*
    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 IncomingDemo
{
    public static void main(String args[]) throws Exception
    {
	SimpleCapi capi=new SimpleCapi("127.0.0.1", 7347);
	capi.acceptCalls();
	boolean running = true;
	while(running)
	{
	    System.out.println("waiting for call...");
	    while(true)
	    {
		CapiEvent event = capi.listen(60);
		if(event.type == capi.CAPI_EVENT_INCOMING)
		{
		    System.out.println("call: "+event.msisdn);
		    System.out.println("answering...");
		    if(capi.answer(event))
			break;
		    else {
			System.out.println("Couldn't answer. Waiting for call...");
		    }
		} else {
		    System.out.println(event);
		}
	    }
//	    int jobid = capi.play("welcome.wav");
	    int jobid = capi.speak("Hello there. Be welcome to I.V.R., The Interactive Voice Response System.");
	    System.out.println("jobid:"+jobid);
	
	    while(true)
	    {
		CapiEvent event = capi.listen(60);
		if(event.type == capi.CAPI_EVENT_DONE &&
		    event.jobid == jobid) {
		    System.out.println("message played, hanging up...");
		    capi.hangup();
		    break;
		} else if (event.type == capi.CAPI_EVENT_HANGUP) {
		    System.out.println("user hung up...");
		    break;
		} else if (event.type == capi.CAPI_EVENT_DIALTONE) {
		    System.out.println("Customer pressed the butten: " + event.tone);
		    capi.stop(jobid);
		}
	    }
	}
        capi.close(); 
    }
}
