/*
 * joystick plugin for VDR
 *
 * mappings.c - axis mapping classes
 *
 * Copyright (C) 2003 Andreas Regel <andreas.regel@powarman.de>
 *
 * This code is distributed under the terms and conditions of the
 * GNU GENERAL PUBLIC LICENSE. See the file COPYING for details.
 */

#include "global.h"
#include "mappings.h"

cMappings Mappings;

cMapping::cMapping()
:	number(0),
	off(0),
	threshold(0)
{
}

bool cMapping::Parse(const char * s)
{
	string str(s);
	int field = 0;
	unsigned int pos = 0;
	unsigned int start = 0;
	string tmp;
	while ((pos = str.find(':', start)) != string::npos)
	{
		tmp = trim(str.substr(start, pos - start));
		if (field == 0)
			number = atoi(tmp.c_str());
		else if (field == 1)
			off = atoi(tmp.c_str()) + 32768;
		else if (field == 2)
			threshold = atoi(tmp.c_str());
		else
			values.push_back(atoi(tmp.c_str()) + 32768);
		start = pos + 1;
		field++;
	}
	tmp = trim(str.substr(start));
		values.push_back(atoi(tmp.c_str()) + 32768);
	if (values.size() < 1)
		return false;
	return true;
}

int cMapping::GetButton(int axisValue, int previousButton)
{
	int previousValue;

	axisValue += 32768;
	if (previousButton == -1)
		previousValue = off;
	else
		previousValue = values[previousButton];
	if (Active(axisValue, previousValue))
		return previousButton;
	if (Active(axisValue, off))
		return -1;
	for (int i = 0; i < (int) values.size(); i++)
	{
		if (Active(axisValue, values[i]))
			return i;
	}
	return -1;
}

bool cMapping::Active(int axisValue, int value)
{
	if (axisValue > value - threshold && axisValue < value + threshold)
		return true;
	else
		return false;
}

cMappings::cMappings()
{
}

bool cMappings::Load(const char * fileName, bool allowComments)
{
	if (cConfig<cMapping>::Load(fileName, allowComments))
	{
		//for (cMapping * mapping = First(); mapping; mapping = Next(mapping))
		//{
		//	printf("%d\n", mapping->Number());
		//}
		return true;
	}
	return false;
}

cMapping * cMappings::GetByNumber(int number)
{
	for (cMapping * mapping = First(); mapping; mapping = Next(mapping))
	{
		if (number == mapping->Number())
			return mapping;
	}
	return NULL;
}

