package com.izouma.nineth.converter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.izouma.nineth.domain.CollectionProperty;
import org.apache.commons.lang3.StringUtils;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.List;

@Converter
public class PropertyListConverter implements AttributeConverter<List<CollectionProperty>, String> {

    @Override
    public String convertToDatabaseColumn(List<CollectionProperty> collectionProperties) {
        if (collectionProperties == null) {
            return null;
        }
        return JSON.toJSONString(collectionProperties);
    }

    @Override
    public List<CollectionProperty> convertToEntityAttribute(String s) {
        if (StringUtils.isEmpty(s)) {
            return null;
        }
        try {
            return JSONArray.parseArray(s, CollectionProperty.class);
        } catch (Exception ignored) {
        }
        return null;
    }
}