/*
 * 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 (c) Ericsson AB, 2004-2007. All rights reserved.
 * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
 */
package org.jvnet.glassfish.comms.clb.proxy.util;

import com.sun.grizzly.util.SSLUtils;
import com.sun.grizzly.util.SelectorFactory;

import org.jvnet.glassfish.comms.clb.proxy.config.LoadBalancerProxyConstants;

import java.io.IOException;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

import javax.net.ssl.SSLEngine;


/**
 *
 * @author Jeanfrancois Arcand
 */
public class Reader {
    // Taken from ByteBufferInputStream impl
    public static int read(ByteBuffer byteBuffer, SocketChannel channel,
        int readTimeout) throws IOException {
        byteBuffer.clear();

        int count = 1;
        int byteRead = 0;
        Selector readSelector = null;
        SelectionKey tmpKey = null;

        try {
            while (count > 0) {
                count = channel.read(byteBuffer);

                if (count > -1) {
                    byteRead += count;
                } else {
                    byteRead = count;
                }
            }

            if (byteRead == 0) {
                readSelector = SelectorFactory.getSelector();

                if (readSelector == null) {
                    return 0;
                }

                count = 1;

                tmpKey = null;
                tmpKey = channel.register(readSelector, SelectionKey.OP_READ);
                tmpKey.interestOps(tmpKey.interestOps() | SelectionKey.OP_READ);

                int code = readSelector.select(readTimeout);
                tmpKey.interestOps(tmpKey.interestOps() &
                    (~SelectionKey.OP_READ));

                if (code == 0) {
                    return 0; // Return on the main Selector and try again.
                }

                while (count > 0) {
                    count = channel.read(byteBuffer);

                    if (count > -1) {
                        byteRead += count;
                    } else {
                        byteRead = count;
                    }
                }
            }
        } finally {
            if (tmpKey != null) {
                tmpKey.cancel();
            }

            if (readSelector != null) {
                try {
                    readSelector.selectNow();
                } catch (IOException ex) {
                    ;
                }

                SelectorFactory.returnSelector(readSelector);
            }
        }

        byteBuffer.flip();

        return byteRead;
    }

    // Taken from sslbytbufferinputstream in grizzly
    public static int doSSLRead(ByteBuffer inputBB, ByteBuffer byteBuffer,
        SelectionKey key, int readTimeout) throws IOException {
        byteBuffer.compact();

        int initialPosition = byteBuffer.position();
        int byteRead = 0;

        // We need to make sure the unwrap worked properly and we have all
        // the packets properly read. If the SSLEngine fail to unwrap all the
        // bytes, the byteBuffer will be empty event if some encrypted bytes
        // are available.
        while (byteBuffer.position() == initialPosition) {
            int currentRead = SSLUtils.doSecureRead(key.channel(),
                    (SSLEngine) (key.attachment()), byteBuffer, inputBB);

            if (currentRead > 0) {
                byteRead += currentRead;
            }

            if ((currentRead > 0) || (inputBB.position() > 0)) {
                try {
                    byteBuffer = SSLUtils.unwrapAll(byteBuffer, inputBB,
                            (SSLEngine) (key.attachment()));
                } catch (IOException ex) {
                    ex.printStackTrace();

                    return -1;
                }
            } else {
                break;
            }
        }

        byteBuffer.flip();

        return byteRead;
    }
}
