package com.actionbazaar.application;

import com.actionbazaar.domain.Bid;
import com.actionbazaar.interfaces.socket.BidEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;

/**
 *  This class acts as an interceptor of method calls, allowing events to be
 *  fired that correspond to specific types of activity, without needing to 
 *  add any of the event firing detail to the target class itself.
 *
 *  Uses CDI.
 */

@Interceptor
@Notify
public class NotifyInterceptor {

    private static final Logger logger = Logger.getLogger(NotifyInterceptor.class.getName());
    
    @Inject
    Event<BidEvent> event;

    /**
     * Intercepts method calls to insert, update, delete bids and fires a
     * CDI event with the details of the bid 
     * 
     * @param context
     * @return
     * @throws Exception 
     */
    @AroundInvoke
    public Object notify(InvocationContext context) throws Exception {
        
        logger.log(Level.INFO, 
                "notify ${0} ${1}", 
                new Object[] { 
                    context.getMethod(),
                    context.getParameters()[0]
                });
        
        String method = context.getMethod().getName();      
        Bid bid = (Bid)context.getParameters()[0];

        BidEvent bidEvent = new BidEvent(bid);
        
        switch(method) {
            case "addBid":
                bidEvent.setType("Add");
                break;
            case "updateBid":
                bidEvent.setType("Update");
                break;
            case "deleteBid":
                bidEvent.setType("Delete");
                break;
        }
        
        
        // Fire the event 
        event.fire(bidEvent);
        return context.proceed();

    }
}
