/*
   SIOManager.C - simple command dispatcher

   Copyright (C) 2002 Matthias Reichl <hias@horus.com>

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include <signal.h>
#include <stdio.h>

#include "SIOManager.h"

#include "AtariDebug.h"

#include "SIOTracer.h"

SIOManager::SIOManager(SIOWrapper* wrapper)
	: fWrapper(wrapper)
{
	int i;
	for (i=0;i<256;i++) {
		fHandlers[i] = 0;
	}
}

SIOManager::~SIOManager()
{
	int i;
	for (i=0;i<256;i++) {
		if (fHandlers[i]) {
			delete fHandlers[i];
			fHandlers[i] = 0;
		}
	}
}

int SIOManager::RegisterHandler(unsigned char device_id, AbstractSIOHandler* handler)
{
	if (fHandlers[device_id]) {
		return 1;
	} else {
		fHandlers[device_id] = handler;
		return 0;
	}
}

int SIOManager::UnregisterHandler(unsigned char device_id)
{
	if (fHandlers[device_id]) {
		fHandlers[device_id] = 0;
		return 0;
	} else {
		return 1;
	}
}

int SIOManager::DoServing(int otherReadPollDevice)
{
	int ret;
	SIO_command_frame frame;
	sigset_t orig_sigset, sigset;

	// setup signal mask to block all signals except KILL, STOP, INT
	sigfillset(&sigset);
	sigdelset(&sigset,SIGKILL);
	sigdelset(&sigset,SIGSTOP);
	sigdelset(&sigset,SIGINT);

	while (1) {
		ret = fWrapper->WaitForCommandFrame(otherReadPollDevice);
		switch (ret) {
		case 0: {

			sigprocmask(SIG_BLOCK, &sigset, &orig_sigset);
				// we don't want to be disturbed...
			
			ret=fWrapper->GetCommandFrame(frame);
		        if (ret == 0 ) {
				if (fHandlers[frame.device_id]) {
					ret = fHandlers[frame.device_id]->ProcessCommandFrame(frame, fWrapper);
				} else {
					SIOTracer::GetInstance()->TraceCommandFrame(frame, "no disk - unhandeled ");
				}
			}

			sigprocmask(SIG_SETMASK, &orig_sigset, NULL);
			break;
		}
		case 1:
			return 0;
		case 2:
			return 1;
		default:
			return -1;
		}
	}
}
