//
// Copyright (c) 2005 PortWise AB. All rights reserved.
//
// This software is the confidential and proprietary information of
// PortWise AB. ("Confidential Information"). You shall not
// disclose such Confidential Information and shall use it only in
// accordance with the terms of the agreement you entered into with
// PortWise AB.
//
// Warning: This computer program is protected by copyright law and
// international treaties. Unauthorized reproduction or distribution
// of this program, or any portion of it, may result in severe civil
// and criminal penalties, and will be prosecuted to the maximum
// extent possible under law.
//

package com.portwise.xpi.epi.plugins.mac;

import java.util.HashMap;
import java.util.StringTokenizer;


/**
 * The AccessHandler that parses the list of MAC addresses and verifies if the end user's MAC
 * address is in the list.
 * 
 * @author PortWise AB
 */
public class AccessHandler
{
    private HashMap mMap;


    /**
     * Constructs a new AccessHandler instance. Parses the list of MAC addresses.
     * 
     * @param clientList The list of MAC addresses.
     */
    public AccessHandler(String clientList)
    {
        mMap = new HashMap();

        StringTokenizer stringtoken = new StringTokenizer(clientList.trim(), ",");
        while (stringtoken.hasMoreTokens())
        {
            StringBuffer parameterbuff = new StringBuffer(stringtoken.nextToken());
            mMap.put((getCorrectMacFormat(parameterbuff.toString())).toLowerCase(), null);
        }
    }


    /**
     * Parses a MAC address and converts it to a unified format.
     * 
     * @param mac The MAC address to convert.
     * @return A MAC address in a unified format.
     */
    synchronized private String getCorrectMacFormat(String mac)
    {
        if (mac != null)
        {
            int index;

            StringBuffer macbuff = new StringBuffer(mac);
            while ((index = macbuff.indexOf(" ")) != -1 || (index = macbuff.indexOf("-1")) != -1
                || (index = macbuff.indexOf(";")) != -1 || (index = macbuff.indexOf("-")) != -1
                || (index = macbuff.indexOf(".")) != -1 || (index = macbuff.indexOf(":")) != -1)
            {
                macbuff.deleteCharAt(index);
            }

            return macbuff.toString();
        }
        return null;
    }


    /**
     * Verfies if an end user's MAC address is in the list of valid addresses. If a wildcard is
     * found in the list of valid addresses this method will always return true.
     * 
     * @param clientMac The end user's MAC address.
     * @return Returns true if the MAC address is found and is valid, otherwise
     *         false.
     */
    synchronized boolean checkAccess(String clientMac)
    {
        if (mMap.containsKey("*"))
        {
            return true;
        }

        return mMap.containsKey(clientMac);
    }
}