/**
 * Copyright 2007-2016, Kaazing Corporation. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.kaazing.gateway.transport;

import java.util.concurrent.Callable;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.AttributeKey;
import org.apache.mina.core.session.IoSession;

/**
 * This is an internal proxy connector used "beneath" the TCP layer.
 */
public class ProxyHandler extends IoHandlerAdapter {

    public static final AttributeKey REMOTE_ADDRESS_KEY = new AttributeKey(ProxyHandler.class, "remoteAddress");
    public static final AttributeKey CREATE_SESSION_CALLABLE_KEY = new AttributeKey(ProxyHandler.class, "createSession");
    public static final AttributeKey FAIL_SESSION_RUNNABLE_KEY = new AttributeKey(ProxyHandler.class, "failSession");
    public static final AttributeKey PROXY_SESSION_KEY = new AttributeKey(ProxyHandler.class, "proxySession");

    protected final ProxyHandler delegate = DirectProxyHandler.DIRECT_PROXY_HANDLER;

    protected void newProxySession(IoSession parent) throws Exception {
        Callable sessionFactory = (Callable)parent.removeAttribute(CREATE_SESSION_CALLABLE_KEY);
        Object newSession = sessionFactory.call();

        parent.setAttribute(PROXY_SESSION_KEY, newSession);
        parent.setAttribute(BridgeConnectHandler.DELEGATE_KEY, delegate);
    }

    protected void failProxySession(IoSession parent) throws Exception {
        Runnable failSession = (Runnable) parent.removeAttribute(FAIL_SESSION_RUNNABLE_KEY);

        failSession.run();
    }

}
