#include "refl/refl.h"
namespace refl {
	template<typename T>
	void malloc_list(T*& ptr, int count) {
		ptr = (T*)malloc(count * sizeof(T));
		for (size_t i = 0; i < count; i++)
		{
			std::construct_at(ptr + i);
		}
	}
	template<typename T>
	class parray {
	protected:
		const UClass* m_cls;
		T* m_ptr;
		int m_count;
	public:
		template<typename C>
		requires std::is_base_of_v<T, C>
		parray(std::vector<C>& vec) : m_cls(&TypeInfo<C>::StaticClass){
			m_count = vec.size();
			if (m_count > 0) {
				malloc_list(m_ptr, m_count);
				std::move(vec.begin(), vec.end(), m_ptr);
			}
		}
		parray(parray<T>& parr) : m_cls(parr.m_cls)
			, m_ptr(parr.data()), m_count(parr.size()) {
			parr.reset();
		}
		~parray() {
			if (!m_count || !m_cls)
				return;
			auto dest = m_cls->vtable.Destruct;
			if (dest) {
				for (int i = 0; i < m_count; i++) {
					dest((char*)m_ptr + (i * m_cls->size));
				}
			}
			m_count = 0;
			m_ptr = nullptr;
		}
		T* at(int i)noexcept {
			if(i < m_count)
				return (T*)((char*)m_ptr + (i * m_cls->size));
			return nullptr;
		}
		T* data() noexcept{
			return m_ptr;
		}
		void reset() noexcept {
			m_ptr = nullptr;
			m_count = 0;
		}
		int size() const noexcept {
			return m_count;
		}
		int capicty() const noexcept {
			return m_count * m_cls->size;
		}
		const UClass* uclass()const noexcept {
			return m_cls;
		}
	};
	template<typename T, typename C>
	parray<T> ToParray(std::vector<C>& vec){
		return parray<T>{vec};
	}
}
