package foodplanet.data.dao;

import foodplanet.data.manager.DataManager;
import foodplanet.data.manager.SpringDataManager;
import foodplanet.data.model.FoodItem;
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 FoodItemDaoImpl implements FoodItemDao{
    private SpringDataManager dm;
    
    public FoodItemDaoImpl() {
    }
    
    public void setDataManager(DataManager dm) {
        this.dm = (SpringDataManager) dm;
    }
    
    public List<FoodItem> findAllFoodItems(long catId) {
        SimpleJdbcTemplate jdbc = dm.getSimpleJdbcTemplate();
        ParameterizedRowMapper<FoodItem> mapper = new FoodItemMapper();
        List<FoodItem> result = null;
        
        String sql = null;
        if(catId == 0){
            sql = dm.getNamedSql("GET_ALL_FOOD_ITEMS");
            result = jdbc.query(sql,mapper);
        }
        else if(catId > 0){
            sql = dm.getNamedSql("GET_ALL_FOOD_ITEMS_BY_CATEGORY");
            result =  jdbc.query(sql,mapper, catId);
        }
        return result;
    }
    
    public FoodItem loadFoodItemById(long id) {
        String sql = dm.getNamedSql("GET_FOOD_ITEM_BY_ID");
        SimpleJdbcTemplate jdbc = dm.getSimpleJdbcTemplate();
        
        ParameterizedRowMapper<FoodItem> mapper = new FoodItemMapper();
        
        return jdbc.queryForObject(sql, mapper, id);
    }
    
    public void updateItemStock(long id) {
        String sql = dm.getNamedSql("UPDATE_STOCK");
        SimpleJdbcTemplate jdbc = dm.getSimpleJdbcTemplate();
        jdbc.update(sql,id);
    }
    
    private class FoodItemMapper implements ParameterizedRowMapper {
        public FoodItem mapRow(ResultSet rs, int row) throws SQLException {
            FoodItem item = new FoodItem();
            item.setId(rs.getLong("itemId"));
            item.setCategoryId(rs.getLong("catId"));
            item.setName(rs.getString("itemName"));
            item.setDescription(rs.getString("itemDesc"));
            item.setImgFile(rs.getString("itemImage"));
            item.setPrice(rs.getFloat("itemPrice"));
            item.setQuantityStocked(rs.getInt("itemQtyStocked"));
            item.setDateCreated(rs.getTimestamp("dateCreated"));
            return item;
        }
    }    
}
