package net.woodyfolsom.cs6601.p3.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.stereotype.Repository;

import net.woodyfolsom.cs6601.p3.domain.Headline;

@Repository
public class HeadlineDaoImpl implements HeadlineDao {
	private static final String DELETE_BY_ID_STMT = "DELETE from headlines WHERE id = ?";
	
	private static final String INSERT_STMT = "INSERT INTO headlines (text, date, stock, dataset) values (?, ?, ?, ?)";
	
	private static final String SELECT_BY_ID_QRY = "SELECT * from headlines WHERE id = ?";
	private static final String SELECT_BY_STOCK_QRY = "SELECT * from headlines WHERE stock = ? AND date = ?";

	private JdbcTemplate jdbcTemplate;
	
	public int deleteById(int headlineId) {
		return jdbcTemplate.update(DELETE_BY_ID_STMT,
				new RequestMapper(), headlineId);
	}
	
	public int insert(Headline headline) {
		return jdbcTemplate.update(INSERT_STMT, headline.getText(), headline.getDate(), headline.getStock(), headline.getDataset());
	}
	
	public Headline select(int headlineId) {
		return jdbcTemplate.queryForObject(SELECT_BY_ID_QRY,
				new RequestMapper(), headlineId);
	}
	
	public List<Headline> select(String stock, Date date) {
		return jdbcTemplate.query(SELECT_BY_STOCK_QRY,
				new RequestMapper(), stock, date);
	}
	
	@Autowired
	public void createTemplate(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	private class RequestMapper implements ParameterizedRowMapper<Headline> {

		@Override
		public Headline mapRow(ResultSet rs, int arg1) throws SQLException {
			Headline headline = new Headline();
			return headline;
		}

	}
}