#pragma once
#include "meta.h"
#include "uclass.h"
#include "convert.h"
namespace refl {

	template<typename T, typename Obj>
	inline FieldPtr Meta::MemberField(T Obj::* ptr, const Name& name, char*& memory, const MemberData& data)
	{
		MemberData member;
		auto cls = &TypeInfo<T*>::StaticClass;
		member.offset = reinterpret_cast<std::size_t>(&(reinterpret_cast<const Obj*>(0)->*ptr));
		if (data.value.IsValid()) {
			member.value = Any(memory, cls);
			assert(Convert::Construct(member.value, data.value));
			memory += member.value.Size();
		}
		if (data.meta.IsValid()) {
			member.meta = data.meta.Change(memory);
			Convert::Construct(member.meta, data.meta);
			memory += data.meta.Size();
		}
		constexpr uint32_t flag = FIELD_MEMBER_FLAG | FIELD_ATTRIBUTE_FLAG;
		return { name, cls, member,flag};
	}
	template<typename R, typename ...Args>
	inline FieldPtr Meta::MethodField(R(*ptr)(Args...), const Name& name, char*& memory, const MethodData& data)
	{
		MethodData method;
		uint32_t flag = FIELD_METHOD_FLAG;
		constexpr auto cls = &TypeInfo<real_type_t<R>(*)(real_type_t<Args>...)>::StaticClass;
		if (data.value.IsValid()) {
			flag |= FIELD_METHOD_VALUE_FLAG;
			AnyArgs args(data.value, cls->GetParams(), memory);
			method.value = args.ToSArray();
			memory += args.Size();
		}
		if (data.meta.IsValid()) {
			method.meta = data.meta.Change(memory);
			Convert::Construct(method.meta, data.meta);
			memory += data.meta.Size();
		}
		method.fptr = { *(Method*)&ptr };
		return { name, cls, method,flag };
	}
	template<typename T, typename R, typename ...Args>
	inline FieldPtr Meta::MethodField(R(T::*ptr)(Args...),const Name& name, char*& memory, const MethodData& data)
	{
		MethodData method;
		uint32_t flag = FIELD_MEMBER_FLAG | FIELD_METHOD_FLAG;
		constexpr auto cls = &TypeInfo<real_type_t<R>(*)(const void*, real_type_t<Args>...)>::StaticClass;
		if (data.value.IsValid()) {
			flag |= FIELD_METHOD_VALUE_FLAG;
			AnyArgs args(data.value, cls->GetParams(), memory);
			method.value = args.ToSArray();
			memory += args.Size();
		}
		if (data.meta.IsValid()) {
			method.meta = data.meta.Change(memory);
			Convert::Construct(method.meta, data.meta);
			memory += data.meta.Size();
		}
		method.fptr = { *(Method*)&ptr };
		return { name, cls, method,flag };
	}
}