/*
 * 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.
 */
package com.ericsson.ssa.container;

import com.ericsson.ssa.container.startup.SipMonitoring;
import com.ericsson.ssa.sip.Dispatcher;
import com.ericsson.ssa.sip.Layer;
import com.ericsson.ssa.sip.SipServletRequestImpl;
import com.ericsson.ssa.sip.SipServletResponseImpl;
import com.ericsson.ssa.sip.dns.TargetResolver;
import com.ericsson.ssa.sip.dns.TargetTuple;

import com.sun.grizzly.Controller;
import com.sun.grizzly.SelectorHandler;
import com.sun.grizzly.util.OutputWriter;
import com.sun.grizzly.util.SSLOutputWriter;
import com.sun.grizzly.util.ThreadAttachment;
import com.sun.grizzly.util.WorkerThread;

import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;

public class StreamResponseDispatcher implements Dispatcher {

    private final SelectorHandler streamHandler;
    private final SocketChannel socketChannel;
    private final Layer backup; //In case of failure using the channel in the context dispatch to backup
    private Logger logger = Logger.getLogger("SipContainer");
    ThreadAttachment currentTA = null;
    private final Lock writeLock = new ReentrantReadWriteLock().writeLock();
    private final ConcurrentLinkedQueue<ByteBuffer> byteBuffersPool;

    public StreamResponseDispatcher(SelectorHandler handler,
            SocketChannel channel, Layer failback) {
        streamHandler = handler;
        socketChannel = channel;
        backup = failback;
        byteBuffersPool = GrizzlyNetworkManager.byteBuffersPool;

        if (handler.protocol() == Controller.Protocol.TLS) {
            currentTA = ((WorkerThread) Thread.currentThread()).detach(true);
        }
    }

    public void dispatch(SipServletRequestImpl req) {
        throw new IllegalStateException("Not designed for connection reuse!");
    }

    public void dispatch(SipServletResponseImpl resp) {

        ByteBuffer bb = byteBuffersPool.poll();
        if (bb == null) {
            bb = ByteBuffer.allocate(GrizzlyNetworkManager.DEFAULT_BB_SIZE);
        }

        try {
            //TODO add a Hash table that makes keeps track if someone is writing and in that case queue.
            if (streamHandler.protocol() == Controller.Protocol.TCP) {
                writeLock.lock();

                resp.toBufferInit();

                while (resp.toBufferHasRemaining()) {
                    bb.clear();
                    resp.toBuffer(bb);

                    bb.flip();
                    OutputWriter.flushChannel(socketChannel, bb);
                }

                writeLock.unlock();
            } else if (streamHandler.protocol() == Controller.Protocol.TLS) {
                ((WorkerThread) Thread.currentThread()).attach(currentTA);
                writeLock.lock();
                resp.toBufferInit();

                while (resp.toBufferHasRemaining()) {
                    bb.clear();
                    resp.toBuffer(bb);

                    bb.flip();
                    SSLOutputWriter.flushChannel(socketChannel, bb);
                }
                writeLock.unlock();
            }

            if (logger.isLoggable(Level.FINE)) {
                //InetSocketAddress remote = resp.getRemote().getSocketAddress();
                logger.fine("Network OUT response --> \r\n" + resp.toString());
            }

            // SipResponse
            if (SipMonitoring.isEnabled(SipMonitoring.NETWORK_MANAGER)) {
                ((NetworkManager) backup).incrEasSentSipResponses();
            }


        } catch (Exception e) {
            try {
                if (logger.isLoggable(Level.FINE)) {
                    logger.log(Level.FINE, "Failed to reuse connection for response", e);
                }
                TargetTuple targetTuple = TargetResolver.getInstance().resolveResponse(resp);
                if (targetTuple != null) {
                    resp.setRemote(targetTuple);
                }
            } catch (Exception ex) {
                if (logger.isLoggable(Level.FINE)) {
                    //InetSocketAddress remote = resp.getRemote().getSocketAddress();
                    logger.fine("Broken connection --> \r\n" + resp.toString());
                }
            }
            backup.dispatch(resp);
        } finally {
            if (bb != null &&
                    bb.capacity() != GrizzlyNetworkManager.DEFAULT_BB_SIZE) {
                bb.clear();
                byteBuffersPool.offer(bb);
            }
        }
    }
}
