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

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

import ru.bitel.bgbilling.apps.inet.access.sa.ProtocolHandlerAdapter;
import ru.bitel.bgbilling.kernel.network.radius.RadiusDictionary;
import ru.bitel.bgbilling.kernel.network.radius.RadiusPacket;
import ru.bitel.bgbilling.kernel.network.radius.RadiusProtocolHandler;

/**
 * Переопределяет NAS-Identifier для поиска устройства, добавляя в зависимости от услуги соответсвующий суффикс (.PPPoE и .IPoE).<br/>
 * Для Accounting'а - в зависимости от User-Name.
 * 
 * @author amir
 */
public class SkatOverrideNasProtocolHandler
    extends ProtocolHandlerAdapter
    implements RadiusProtocolHandler
{
    private static final Logger logger = LogManager.getLogger();

    /**
     * <pre>
     * VALUE VasExperts-Service-Type Auth 0 # L3-authorization, known IP
     *VALUE VasExperts-Service-Type DHCP 1 # DHCP
     *VALUE VasExperts-Service-Type PAP 2 # PAP authorization
     *VALUE VasExperts-Service-Type CHAP 3 # CHAP authorization
     *VALUE VasExperts-Service-Type MS_CHAPv2 4 # MS-CHAPv2 authorization
     *VALUE VasExperts-Service-Type MAC_QinQ 5 # MAC/QinQ authorization
     *VALUE VasExperts-Service-Type ARP 6 # ARP
     *VALUE VasExperts-Service-Type DHCPv6 7 # DHCPv6
     * </pre>
     */
    @Override
    public String overrideNasIdentifier( final RadiusPacket request )
        throws Exception
    {
        final String nasIdentifier = request.getStringAttribute( -1, RadiusDictionary.NAS_Identifier, null );
        if ( nasIdentifier == null )
        {
            logger.info( "Attribute Nas-Identifier not found" );
            return null;
        }

        // в Access-Request присутствует атрибут VasExperts-Service-Type
        if ( request.getCode() == RadiusPacket.ACCESS_REQUEST )
        {
            final int serviceType = request.getIntAttribute( 43823, 6, -1 ); // VasExperts-Service-Type

            switch( serviceType )
            {
                case 0:
                case 1:
                case 5:
                case 6:
                case 7:
                    return nasIdentifier + ".IPoE";

                default:
                    return nasIdentifier + ".PPPoE";
            }
        }
        else
        {
            final String clazz = request.getStringAttribute( -1, RadiusDictionary.Class, null );
            if ( clazz != null && clazz.contains( "IPoE" ) )
            {
                return nasIdentifier + ".IPoE";
            }
            else
            {
                return nasIdentifier + ".PPPoE";
            }
        }
    }
}
