package foodplanet.management;

import java.io.Serializable;
import java.util.Date;
import javax.management.Notification;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.jmx.export.notification.NotificationPublisher;
import org.springframework.jmx.export.notification.NotificationPublisherAware;

@ManagedResource
public class FoodItemMbeanImpl implements FoodItemMbean, NotificationPublisherAware, Serializable {
    Log log = LogFactory.getLog(FoodItemMbeanImpl.class);
    private Date lastPurchaseDate;
    private long totalPurchased;
    private int minQty;
    private NotificationPublisher notifier;
    
    public FoodItemMbeanImpl() {
    }
    
    @ManagedOperation
    public void incTotalQtyPurchased() {
        totalPurchased++;
        lastPurchaseDate = new Date();
    }

    @ManagedAttribute
    public long getTotalQtyPurchased() {
        return totalPurchased;
    }
    
    @ManagedAttribute
    public void setMinStockQty(int qty) {
        this.minQty = qty;
    }

    @ManagedAttribute
    public int getMinStockQty() {
        return this.minQty;
    }

    @ManagedAttribute
    public String getLastPurchaseDate() {
        return (lastPurchaseDate != null) ? 
            lastPurchaseDate.toString() : "UNKNOWN";
    }

    public void setNotificationPublisher(NotificationPublisher notifier) {
        this.notifier = notifier;
    }
    
    public void sendLowStockNotification(long itemId, int qtyLeft) {
        int sequenceNum = new java.util.Random().nextInt();
        String msg = "Food Item ID: " + itemId + " Stock running low : " + qtyLeft;
        Notification note = new Notification("LOW_STOCK", this, sequenceNum, msg);
        notifier.sendNotification(note);
        log.info("*** Sending LOW_STOCK Notification ***");
    }
}
