
package foodplanet.aspects.listeners;

import foodplanet.data.manager.DataManager;
import foodplanet.data.manager.SpringDataManager;
import foodplanet.management.FoodItemMbean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

public class FoodItemAspectImpl implements FoodItemAspect{
    Log log = LogFactory.getLog(FoodItemAspectImpl.class);
    private SpringDataManager dm;
    private FoodItemMbean mbean;
    public void setDataManager(DataManager dm) {
        this.dm = (SpringDataManager) dm;
    }
    public FoodItemAspectImpl() {
    }

    public void doBeforeStockUpdate(long id) {
        log.info("**** AOP: FoodItemAspect - Before Advice ****");
    }

    public void doAfterStockUpdate(long id) {
        log.info("**** AOP: FoodItemAspect - After Advice ****");
        mbean.incTotalQtyPurchased();
        int qtyLeft = getQtyLeft(id);
        if(qtyLeft <= mbean.getMinStockQty()) {
            mbean.sendLowStockNotification(id, qtyLeft);
        }
    }
    
    private int getQtyLeft(long id) {        
        String sql = dm.getNamedSql("GET_QTY_STOCKED");
        SimpleJdbcTemplate jdbc = dm.getSimpleJdbcTemplate();
        return jdbc.queryForInt(sql, id);
    }
    
    public void setFoodItemMbean(FoodItemMbean mbean) {
        this.mbean = mbean;
    }
}
