package com.izouma.nineth.converter;

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

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Converter
public class FileObjectListConverter implements AttributeConverter<List<FileObject>, String> {
    @Override
    public String convertToDatabaseColumn(List<FileObject> list) {
        if (list != null)
            return JSON.toJSONString(list);
        return null;
    }

    @Override
    public List<FileObject> convertToEntityAttribute(String s) {
        if (StringUtils.isNotEmpty(s)) {
            if (!Pattern.matches("\\[.+]", s)) {
                return Arrays.stream(s.split(",")).map(ss -> {
                    FileObject fileObject = new FileObject();
                    fileObject.setUrl(ss);
                    return fileObject;
                }).collect(Collectors.toList());
            }
            try {
                return JSON.parseArray(s, FileObject.class);
            } catch (Exception e) {

            }
        }
        return null;
    }
}
