package ru.bitel.bgbilling.modules.inet.dyn.device.redback;

import java.net.InetAddress;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import ru.bitel.bgbilling.kernel.network.dhcp.DhcpProtocolHandler;
import ru.bitel.bgbilling.kernel.network.radius.RadiusAttribute;
import ru.bitel.bgbilling.kernel.network.radius.RadiusDictionary;
import ru.bitel.bgbilling.kernel.network.radius.RadiusPacket;
import ru.bitel.bgbilling.kernel.network.radius.RadiusProtocolHandler;
import ru.bitel.bgbilling.modules.inet.common.bean.InetDevice;
import ru.bitel.bgbilling.modules.inet.common.bean.InetDeviceType;
import ru.bitel.bgbilling.server.util.Setup;
import ru.bitel.common.ParameterMap;
import ru.bitel.common.Utils;
import ru.bitel.common.sql.ConnectionSet;

public class SmartEdgeStaticClipsProtocolHandler
	extends SmartEdgeProtocolHandler
	implements RadiusProtocolHandler, DhcpProtocolHandler
{
	private static final Logger logger = LogManager.getLogger();

	@Override
	public void init( Setup setup, int moduleId, InetDevice inetDevice, InetDeviceType inetDeviceType, ParameterMap deviceConfig )
		throws Exception
	{
		super.init( setup, moduleId, inetDevice, inetDeviceType, deviceConfig );
	}

	/**
	 * В постобработке проставляем Framed-IP-Address и Framed-Route.
	 */
	@Override
	public void postprocessAccessRequest( final RadiusPacket request, final RadiusPacket response, final ConnectionSet connectionSet )
		throws Exception
	{
		final String userName = request.getStringAttribute( -1, RadiusDictionary.User_Name, null );

		try
		{
			final InetAddress inetAddress = InetAddress.getByName( userName );
			final byte[] address = inetAddress.getAddress();

			response.setAttribute( new RadiusAttribute.RadiusAttributeIpAddr( -1, RadiusDictionary.Framed_IP_Address, Utils.convertBytesToInt( address ) ) );
		}
		catch( Exception e )
		{
			if( logger.isInfoEnabled() )
			{
				logger.info( "IP-address not found " + userName + ": " + e.getMessage() );
			}
		}

		super.postprocessAccessRequest( request, response, connectionSet );
	}
}
