package com.airbiquity.mcs.echo;

import android.util.Log;

import com.airbiquity.mcs.common.IMCSConnectionAddress;
import com.airbiquity.mcs.common.IMCSMultiPointLayer;
import com.airbiquity.mcs.common.IMcsConListener;
import com.airbiquity.mcs.common.MCSException;
import com.airbiquity.mcs.common.McsLayer;
import com.airbiquity.mcs.tcpip.TCPIPAddress;

public class EchoPortListener implements IMcsConListener{
	
	
	private static final String TAG = "TTCPPortListener";
	private static final int PORT = 7;
	private IMCSMultiPointLayer lowerLayer;


	@Override
	public void newConnectionRequested(IMCSConnectionAddress fromAddress, IMCSConnectionAddress toAddress, byte[] payload) {
		

        if( lowerLayer != null && toAddress instanceof TCPIPAddress && fromAddress instanceof TCPIPAddress )
        {
            TCPIPAddress addrFrom = (TCPIPAddress) fromAddress;
            TCPIPAddress addrTo = (TCPIPAddress) toAddress;
            if( addrFrom.getPortType() == TCPIPAddress.ProtocolTypeTCP && addrTo.getPortType() == TCPIPAddress.ProtocolTypeTCP && (addrTo.getPortNumber() == PORT) )
            {
                try
                {
                    // Create new connection point
                	Log.d(TAG, "Create new connection point");
                    McsLayer layer = lowerLayer.createConnectionPoint( addrFrom, addrTo );
                    EchoLayer ttcpLayer = new EchoLayer();
                    ttcpLayer.setLowerLayer( layer );
                }
                catch( MCSException ex )
                {
                    Log.e( TAG, "", ex );
                }
            }
        }
    
		
	}

	@Override
	public void onConnectionClosed(McsLayer connection, IMCSConnectionAddress fromAddress, IMCSConnectionAddress toAddress) {
	}
	
	
    /**
     * Set the lower layer and start listening to it.
     * If there is a lower layer set already - unset it first. 
     * @param lower_layer : the lower layer which supports TCPIP connections.
     */
    public void setLowerLayer( IMCSMultiPointLayer lower_layer )
    {
        if( lowerLayer != null ){
            lowerLayer.removeListener( this );
        }
        lowerLayer = lower_layer;
        if( lowerLayer != null ){
            lowerLayer.addListener( this );
        }
    }

}
