package foodplanet.data.dao;

import foodplanet.data.manager.DataManager;
import foodplanet.data.manager.SpringDataManager;
import foodplanet.data.model.Category;
import foodplanet.data.model.DataModel;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;


public class CategoryDaoImpl implements CategoryDao{
    private SpringDataManager dm;
    
    public CategoryDaoImpl() {
    }
    
    public void setDataManager(DataManager dm) {
        this.dm = (SpringDataManager) dm;
    }
    
    public List<Category> findAllCategories() {
        String sql = dm.getNamedSql("GET_ALL_CATEGORIES");
        SimpleJdbcTemplate jdbc = dm.getSimpleJdbcTemplate();
        ParameterizedRowMapper<Category> mapper = new CategoryMapper();
        
        return jdbc.query(sql,mapper);
    }
    
    public Category loadCategoryById(long id) {
        String sql = dm.getNamedSql("GET_CATEGORY_BY_ID");
        SimpleJdbcTemplate jdbc = dm.getSimpleJdbcTemplate();
        
        ParameterizedRowMapper<Category> mapper = new CategoryMapper();
        
        return jdbc.queryForObject(sql, mapper, id);
    }
    
    private class CategoryMapper implements ParameterizedRowMapper {
        public Category mapRow(ResultSet rs, int row) throws SQLException {
            Category cat = new Category();
            cat.setId(rs.getInt("catId"));
            cat.setName(rs.getString("catName"));
            cat.setDateCreated(rs.getTimestamp("dateCreated"));
            return cat;
        }
    }
}