package de.oaa.xxx.games.chastity.spinningwheel;

import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;

@Converter
public class SpinningWheelConverter implements AttributeConverter<List<SpinningWheelEntry>, String> {

	private static final ObjectMapper mapper = new ObjectMapper();

	@Override
	public String convertToDatabaseColumn(List<SpinningWheelEntry> list) {
		if (list == null || list.isEmpty())
			return null;
		try {
			return mapper.writeValueAsString(list);
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public List<SpinningWheelEntry> convertToEntityAttribute(String json) {
		if (json == null || json.isBlank())
			return new ArrayList<>();
		try {
			return new ArrayList<>(mapper.readValue(json, new TypeReference<List<SpinningWheelEntry>>() {
			}));
		} catch (Exception e) {
			return new ArrayList<>();
		}
	}
}
