package eu.dnetlib.openaire.common;

import java.sql.Array;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import javax.sql.DataSource;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Created by claudio on 05/07/2017.
 */
@Converter
public class ConverterTextArray implements AttributeConverter<List<String>, Array>, ApplicationContextAware {

	private ApplicationContext applicationContext;

	@Override
	public Array convertToDatabaseColumn(List<String> attribute) {

		final Map<String, DataSource> datasources = applicationContext.getBeansOfType(DataSource.class);
		DataSource source = datasources.values().stream().findFirst().get();

		try {
			Connection conn = source.getConnection();
			return conn.createArrayOf("text", attribute.toArray());

		} catch (SQLException e) {
			e.printStackTrace();
		}

		return null;

	}

	@Override
	public List<String> convertToEntityAttribute(Array dbData) {
		try {
			return Arrays.stream((Object[]) dbData.getArray()).map(d -> (String) d).collect(Collectors.toList());
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
}
