/* 3conf.cpp

some demonstration routines for the SimpleCapi interface.

Part of the caiviar package. 

Copyright (c) 2002 MobileX AG, http://www.mobilexag.de
Copyright (c) 2002 Matthias Kramm <kramm@quiss.org>

This file is distributed under the GPL, see file COPYING for details. */

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <SimpleCapi.h>

class CapiTest {
public:

    /* starts playing a sound file and waits for it's completion */
    void playthrough(SimpleCapi*capi, int line, char*name) {
        int playjob = capi->play (line, name);
	if(!playjob) {
	    printf("Couldn't play %s. File not found?\n", name);
	    exit(1);
	}
        int done = 0;
        while (!done) {
            ISDNEvent event = capi->listen(line, 0);
            switch (event.type) {
		case CAPI_EVENT_DONE:
		    if (event.jobid == playjob)
			done = 1;
		    break;
		case CAPI_EVENT_HANGUP:  
		    printf("Couldn't play %s- other end hung up.\n", name);
		    exit(0);
            }
        }
    }

    /* wait for an incoming call, play a message to him,
       put him on hold, call an operator, play a message
       to him also, then connect the two */ 
    void testforward() {
	Logger * log = new Logger(5);
	log->setFileLogging("capi.log", 5);
        SimpleCapi capi(log);
        int line=capi.open ("32");
	if(line<0)
	    exit(1);
        int ret, done;
        capi.acceptCalls (line);
        while(1) {
            ISDNEvent event;
            event = capi.listen(line, 0);
            if(event.type == CAPI_EVENT_INCOMING) {
                capi.answer(line, &event);
                break;
            }
        }
        usleep(1000000);
        playthrough(&capi, line, "youarebeingconnected.wav");

        if(!capi.hold(line))
	    return;
        
        ret = capi.call (line, "45", 60);

	if(ret) {
	    /* we couldn't contact the callcenter. Play an
	       excuse to the caller and hang up */
	    if(!capi.retrieve(line))
		return;
	    playthrough(&capi, line, "sorry_our_callcenter_is_down.wav");
	    capi.hangup(line);
	    capi.close(line);
	    return;
	}

        usleep(1000000);
        playthrough(&capi, line, "thereisacaller.wav");

        ret = capi.supplemental(line, "3pty");
        done = 0;
        while (!done) {
            ISDNEvent event = capi.listen(line, 0);
            if(event.type == CAPI_EVENT_DONE)
                printf("3pty jobid: %d, got jobid: %d\n", ret, event.jobid);
            break;
        }

	/* both persons with hear this */
        playthrough(&capi, line, "beep.wav");

        while(1) {
            ISDNEvent event = capi.listen(line,60);
	    /* we retrieve only hangup signals from the callcenter */
	    if(event.type == CAPI_EVENT_HANGUP) {
		return;
	    }
	}
    }
};

int main(int argn, char*argv[]) {
    CapiTest t;
    t.testforward();
    return 0;
}

