/*
 * 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.sip.Dispatcher;
import com.ericsson.ssa.sip.Layer;
import com.ericsson.ssa.sip.SipServletRequestImpl;
import com.ericsson.ssa.sip.SipServletResponseImpl;

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.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();

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

        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) {
        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();
                OutputWriter.flushChannel(socketChannel,
                    (ByteBuffer) resp.toBuffer().flip());
                writeLock.unlock();
            } else if (streamHandler.protocol() == Controller.Protocol.TLS) {
                ((WorkerThread) Thread.currentThread()).attach(currentTA);
                writeLock.lock();
                SSLOutputWriter.flushChannel(socketChannel,
                    (ByteBuffer) resp.toBuffer().flip());
                writeLock.unlock();
            }

            if (logger.isLoggable(Level.FINE)) {
                //InetSocketAddress remote = resp.getRemote().getSocketAddress();
                logger.fine("Sent response OUT :\n" + resp.toString());
            }
        } catch (Exception e) {
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE,
                    "Failed to reuse connection for response", e);
            }

            backup.dispatch(resp);
        }
    }
}
