package eu.dnetlib.goldoa.service;

import eu.dnetlib.goldoa.domain.Funder;
import eu.dnetlib.goldoa.domain.Vocabulary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

/**
 * Created by antleb on 5/6/15.
 */
public class FunderManagerImpl implements FunderManager {

    @Autowired
    private DataSource dataSource;

    private final static String SEARCH_FUNDERS = "select id, name from funder where lower(name) like lower(?)";
    private final static String GET_FUNDER = "select id, name, url, source from funder where id=?";

    @Override
    public List<Vocabulary> search(String term) {
        return new JdbcTemplate(dataSource).query(SEARCH_FUNDERS,  new String[]{"%" + term + "%"}, new int[]{Types.VARCHAR}, new RowMapper<Vocabulary>() {
            @Override
            public Vocabulary mapRow(ResultSet rs, int rowNum) throws SQLException {
                return new Vocabulary(rs.getString("id"), rs.getString("name"));
            }
        });
    }

    @Override
    public Funder getById(String id) {
        try {
            return new JdbcTemplate(dataSource).queryForObject(GET_FUNDER, new String[]{id}, new int[]{Types.VARCHAR}, new RowMapper<Funder>() {
                @Override
                public Funder mapRow(ResultSet rs, int rowNum) throws SQLException {
                    return new Funder(rs.getString("id"), rs.getString("name"), rs.getString("url"), rs.getString("source"));
                }
            });
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }
}
