#include "interrupt.h"
#include <iostream>

#include <mutex>
#include <set>

using namespace std;

static mutex imutex;

static set<boolPointer> thePointers;

void registerBoolForInterrupt(boolPointer p)
{
//	std::cerr<<"Register\n";
	scoped_lock L(imutex);
	thePointers.insert(p);
}

void unregisterBoolForInterrupt(boolPointer p)
{
//	std::cerr<<"UnRegister\n";
	scoped_lock L(imutex);
	thePointers.erase(p);
}

void setRegisteredBools()
{
	scoped_lock L(imutex);
	for(auto p:thePointers)
	{
//		std::cerr<<"SETTING to true\n";
		*p=true;
	}
}

// This part is platform specific and probably not correct

#if 1
#include <csignal>
#include <stdio.h>
#include <stdlib.h>



class InterruptHandler
{
	static void handler(int sig)
	{
		std::cerr<<"INTERRUPT\n";
		setRegisteredBools(); //Deadlock if interrupt happens while imutex is locked

		/* To avoid deadlock, one could make a thread whose only job was to once in a while check if a bool had been set by an interrupt handler. In that case the thread should call setRegisteredBools. */
		/* It not safe to call printf from a signal handler. It should be checked that using std::cerr in an interrupt handler is also not ok.*/
	}
public:
	InterruptHandler()
	{
		signal(SIGTERM, handler);
	}
};

static InterruptHandler theHandler;

#endif
