package com.izouma.nineth.converter;

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

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

@Converter
public class PrivilegeListConverter implements AttributeConverter<List<Privilege>, String> {

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

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