/*
    PIP - Platform Independent Primitives
    C++ code info structs
    Ivan Pelipenko peri4ko@yandex.ru

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 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 Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "picodeinfo.h"

#include "pivariant.h"


PIString PICodeInfo::EnumInfo::memberName(int value_) const {
	for (const auto & e: members)
		if (e.value == value_) return e.name.toString();
	return PIString();
}


int PICodeInfo::EnumInfo::memberValue(const PIString & name_) const {
	for (const auto & e: members)
		if (e.name.toString() == name_) return e.value;
	return -1;
}


PIVariantTypes::Enum PICodeInfo::EnumInfo::toPIVariantEnum() {
	PIVariantTypes::Enum en(name.toString());
	for (auto m: members)
		en << m.toPIVariantEnumerator();
	if (!en.isEmpty()) en.selectValue(members.front().value);
	return en;
}


PIVariant PICodeInfo::getMemberAsVariant(const void * p, const char * class_name, const char * member_name) {
	if (!p || !class_name || !member_name) return PIVariant();
	AccessTypeFunction atf  = PICODEINFO::accessTypeFunctions().value(class_name, (AccessTypeFunction) nullptr);
	AccessValueFunction avf = PICODEINFO::accessValueFunctions().value(class_name, (AccessValueFunction) nullptr);
	if (!atf || !avf) return PIVariant();
	return PIVariant::fromValue(avf(p, member_name), PIStringAscii(atf(member_name)));
}


PICodeInfo::__Storage__::__Storage__() {
	classesInfo           = new PIMap<PIConstChars, ClassInfo *>;
	enumsInfo             = new PIMap<PIConstChars, EnumInfo *>;
	accessValueFunctions  = new PIMap<PIConstChars, AccessValueFunction>;
	accessTypeFunctions   = new PIMap<PIConstChars, AccessTypeFunction>;
	accessOffsetFunctions = new PIMap<PIConstChars, AccessOffsetFunction>;
	(*enumsInfo)[""]      = new EnumInfo();
}


PICodeInfo::__Storage__::~__Storage__() {
	piDeleteAll(classesInfo->values());
	piDeleteAll(enumsInfo->values());
	piDeleteSafety(classesInfo);
	piDeleteSafety(enumsInfo);
	piDeleteSafety(accessValueFunctions);
	piDeleteSafety(accessTypeFunctions);
	piDeleteSafety(accessOffsetFunctions);
}


PICodeInfo::__Storage__ * PICodeInfo::__Storage__::instance() {
	static __Storage__ ret;
	return &ret;
}


PICodeInfo::ClassInfoInterface classesInfo;
PICodeInfo::EnumsInfoInterface enumsInfo;
PICodeInfo::AccessValueFunctionInterface accessValueFunctions;
PICodeInfo::AccessTypeFunctionInterface accessTypeFunctions;
