/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */
package com.sun.enterprise.web.connector.grizzly;

import java.io.IOException;
import java.util.logging.Level;

/**
 * This task execute and then notify its listener, which usualy execute on 
 * their own thread. The task perform the same operation as its parent,
 * but the attached <code>ProcessorTask</code> execute on its own thread.
 *
 * @author Jean-Francois Arcand
 */
public class AsyncReadTask extends ReadTask {
   
    public AsyncReadTask(){
        super();
    }
    
    
    public AsyncReadTask(StreamAlgorithm algorithm,
                    boolean useDirectByteBuffer, boolean useByteBufferView){
        super(algorithm,useDirectByteBuffer,useByteBufferView);
    }

    // ----------------------------------------------------------------------//
    
    /**
     * Manage the <code>SelectionKey</code>
     */
    protected void manageKeepAlive(boolean keepAlive,int count, 
            Exception exception){         

        // The key is invalid when the Task has been cancelled.
        if ( count == -1 || !key.isValid() || exception != null){
            if ( exception != null){
                // Make sure we have detached the processorTask
                detachProcessor();
                SelectorThread.logger().log(Level.FINEST, "SocketChannel Read Exception: "
                        ,exception);
            }
            terminate(true);
        }
    }


    /**
     * Execute the <code>ProcessorTask</code> 
     * @return false if the request wasn't fully read by the channel.
     *         so we need to respin the key on the Selector.
     */
    public boolean executeProcessorTask() throws IOException{                  
        boolean registerKey = false;
        
        if (SelectorThread.logger().isLoggable(Level.FINEST))
            SelectorThread.logger().log(Level.FINEST,"executeProcessorTask");
        
        if ( algorithm.getHandler()
                .handle(null, Handler.REQUEST_BUFFERED) == Handler.BREAK ){
            return true;
        }
        
        // Get a processor task. If the processorTask != null, that means we
        // failed to load all the bytes in a single channel.read().
        if (processorTask == null){
            attachProcessor(selectorThread.getProcessorTask());
        } else {
            // When spawnProcessorTask is true, we must reconfigure the 
            // ProcessorTask
            configureProcessorTask();
        }        
        
        if (taskEvent == null){
            taskContext = new TaskContext();
            taskEvent = new TaskEvent<TaskContext>(taskContext);
        }
        
        // Call the listener and execute the task on it's own pipeline.
        taskEvent.setStatus(TaskEvent.START);        
        taskContext.setInputStream(inputStream);
        taskEvent.attach(taskContext);
        fireTaskEvent(taskEvent); 
        return false;
    }

      
    /**
     * Complete the transaction.
     */
    public void terminate(boolean keepAlive){          
        // Safeguard to avoid returning the instance more than once.
        if ( isReturned ){
            return;
        }
        
        if (processorTask != null && processorTask.connectionHeaderValue){
            detachProcessor();        
            registerKey(); 
            recycle();            
            returnTask();
        } else {
            super.terminate(keepAlive);    
        }
    }
    
    
    /**
     * Set appropriate attribute on the <code>ProcessorTask</code>.
     */
    public void configureProcessorTask(){
        super.configureProcessorTask();
        if ( !getTaskListeners().contains(processorTask) ){
            processorTask.addTaskListener(this);
            addTaskListener(processorTask);
        }
    } 
}
