package weber_4_0_sample.org.itscool.seiseki;
import java.util.LinkedList;


import org.itscool.weber.action.Action;
import org.itscool.weber.action.ActionBucket;

public class SeisekiSaveAction extends Action {
    public String doExecute(ActionBucket bucket)
    throws Exception {
        Seiseki data = (Seiseki)bucket.getForm();            
        if (this.getParameter("save") != null) {
            LinkedList messages = 
            (LinkedList)bucket.getAttributeFromSession ("messages");
            if(messages == null){
                messages = new LinkedList();
                bucket.setAttributeFromSession( "messages", messages);
            }
            messages.addFirst(data); 
            return "list";
        }else if(this.getParameter("delete") != null){
            LinkedList messages = 
            (LinkedList)bucket.getAttributeFromSession ("messages");
            if(messages == null){
                messages = new LinkedList();
                bucket.setAttributeFromSession( "messages", messages);
            }
            
            int id = data.getId();
            deleteMessage(messages, id);
            
            return "list";
        }else if(this.getParameter("edit") != null){
            bucket.setAttribute("ask", data);
            return "input";
        }else{
            bucket.setAttribute("ask", data);
            return "confirm";
        } 
    }
    
    public void deleteMessage(LinkedList messages, int id){
        for(int i=0; i<messages.size(); i++){
            Seiseki ask = (Seiseki)messages.get(i);
            if( ask.getId() == id ){
                messages.remove(i);
                break;
            }
        }
    }
}
