/** BEGIN COPYRIGHT BLOCK
 * Copyright (C) 2001 Sun Microsystems, Inc.  Used by permission.
 * Copyright (C) 2005 Red Hat, Inc.
 * All rights reserved.
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; version 2
 * of the License.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 * 
 * END COPYRIGHT BLOCK **/
package com.netscape.management.admserv.panel;

import java.util.*;
import java.net.*;
import com.netscape.management.client.util.*;
import com.netscape.management.client.console.ConsoleInfo;
import com.netscape.management.admserv.config.*;

/**
  *
  * @version 0.1 11/28/97
  * @author miodrag@netscape.com
  */
public class CGISNMPSetup extends CGIDataModel {
    private static String _taskURL = "admin-serv/tasks/Configuration/SNMPSetup";

    // String used as keys in the Hashtable for a community entry
    public static final String COMMUNITY_NAME = "community";
    public static final String COMMUNITY_OPERATION = "operation";

    // String used as keys in the Hashtable for a manager entry
    public static final String MANAGER_NAME = "mananger";
    public static final String MANAGER_PORT = "port";
    public static final String MANAGER_COMMUNITY = "community";

    public CGISNMPSetup(ConsoleInfo consoleInfo) {
        super(consoleInfo, _taskURL);
    }


    public static int findEntry(Vector list, String propName,
            String propValue) {
        for (int i = 0; i < list.size(); i++) {
            Hashtable entry = (Hashtable) list.elementAt(i);
            String prop = (String) entry.get(propName);
            if (prop.equals(propValue)) {
                return i;
            }
        }
        return -1;
    }


    /***************************
      * COMMUNITY Strings methods
      ***************************/

    public static Hashtable createCommunityEntry(String community,
            String operation) {
        Hashtable entry = new Hashtable();
        entry.put(COMMUNITY_NAME, community);
        entry.put(COMMUNITY_OPERATION, operation);
        return entry;
    }

    /**
      * Parse a comma separated list of community entries into a vector
      * of hashtable entries containing parametrs (hash keys) COMMUNITY and
      * OPERATION
     */
    public static Vector stringToCommunityVector(String value)
            throws ValidationException {

        if (value == null) {
            throw new ValidationException("", "Community list is undefined");
        }

        // Dash character is used as a special value to denote an empty list
        if (value.equals("-")) {
            return new Vector();
        }

        Vector v = CGIDataModel.commaStringToVector(value);
        for (int i = 0; i < v.size(); i++) {
            String rawValue = (String) v.elementAt(i);
            v.setElementAt(stringToCommunityEntry(rawValue), i);
        }
        return v;
    }

    /**
      * Parse string representation for a single community entry. The format is:
      * <commutity name><TAB><operation>
      * where operation is ALL | SET | GET
     */
    public static Hashtable stringToCommunityEntry(String value)
            throws ValidationException {
        String community = null, operation = null;
        int idx = value.indexOf("\t");
        if (idx < 1) {
            throw new ValidationException("<" + value + ">", "Field separator <TAB> not found");
        }
        community = value.substring(0, idx);
        operation = value.substring(idx + 1);

        //Debug.println("community={" + community + "} operation={" + operation + "}");
        if (operation.equals("ALL") || operation.equals("SET") ||
                operation.equals("GET")) {

            return createCommunityEntry(community, operation);
        } else {
            throw new ValidationException("<" + operation + ">", "Bad value for operation");
        }
    }

    /**
      * Expand community list into String
     */
    public static String communityVectorToString(Vector v)
            throws ValidationException {
        String value = null;
        for (int i = 0; i < v.size(); i++) {
            Hashtable entry = (Hashtable) v.elementAt(i);
            if (value == null) {
                value = communityEntryToString(entry);
            } else {
                value += "," + communityEntryToString(entry);
            }
        }
        // Dash character is used as a special value to denote an empty list
        return (value == null) ? "-" : value;
    }

    /**
      * Expand community entry into String
     */
    public static String communityEntryToString(Hashtable entry)
            throws ValidationException {
        String value = null;
        if (entry.get(COMMUNITY_NAME) == null) {
            Thread.currentThread().dumpStack();
            Debug.println("Community property " + COMMUNITY_NAME + " not found");

        }
        if (entry.get(COMMUNITY_OPERATION) == null) {
            Thread.currentThread().dumpStack();
            Debug.println("Community property " + COMMUNITY_OPERATION +
                    " not found");

        }
        value = (String) entry.get(COMMUNITY_NAME) + "\t" +
                (String) entry.get(COMMUNITY_OPERATION);
        return value;
    }


    /***************************
      * SNMP MANAGER methods
      ***************************/

    public static Hashtable createManagerEntry(String manager,
            String port, String community) {
        Hashtable entry = new Hashtable();
        entry.put(MANAGER_NAME, manager);
        entry.put(MANAGER_PORT, port);
        entry.put(MANAGER_COMMUNITY, community);
        return entry;
    }

    /**
      * Parse a comma separated list of manager entries into a vector
      * of hashtable entries containing parametrs (hash keys) MANAGER and
      * PORT
     */
    public static Vector stringToManagerVector(String value)
            throws ValidationException {

        if (value == null) {
            throw new ValidationException("", "Manager list is undefined");
        }

        // Dash character is used as a special value to denote an empty list
        if (value.equals("-")) {
            return new Vector();
        }

        Vector v = CGIDataModel.commaStringToVector(value);
        for (int i = 0; i < v.size(); i++) {
            String rawValue = (String) v.elementAt(i);
            v.setElementAt(stringToManagerEntry(rawValue), i);
        }
        return v;
    }

    /**
      * Parse string representation for a single manager entry. The format is:
      * <commutity name><TAB><port><TAB><community>
     */
    public static Hashtable stringToManagerEntry(String value)
            throws ValidationException {
        String manager = null, port = null, community = null;
        int tab1 = value.indexOf("\t");
        if (tab1 < 1) {
            throw new ValidationException("<" + value + ">", "Field separator <TAB> not found");
        }
        int tab2 = value.indexOf("\t", tab1 + 1);
        if (tab2 < 1) {
            throw new ValidationException("<" + value + ">", "Second field separator <TAB> not found");
        }

        manager = value.substring(0, tab1);
        port = value.substring(tab1 + 1, tab2);
        community = value.substring(tab2 + 1);

        Debug.println("manager={" + manager + "} port={" + port +
                "} community={" + community + "}");
        try {
            int portValue = Integer.parseInt(port);
            if (portValue < 1 || portValue > 65535) {
                ResourceSet rs = new ResourceSet("com.netscape.management.admserv.panel.panel");
                String msg = rs.getString("common","PortRange");
                throw new ValidationException("", msg);
            }
        } catch (Exception ex) {
            ResourceSet rs = new ResourceSet("com.netscape.management.admserv.panel.panel");
            String msg = rs.getString("common","PortRange");
            throw new ValidationException("", msg);
        }


        return createManagerEntry(manager, port, community);
    }

    /**
      * Expand manager list into String
     */
    public static String managerVectorToString(Vector v)
            throws ValidationException {
        String value = null;
        for (int i = 0; i < v.size(); i++) {
            Hashtable entry = (Hashtable) v.elementAt(i);
            if (value == null) {
                value = managerEntryToString(entry);
            } else {
                value += "," + managerEntryToString(entry);
            }
        }
        // Dash character is used as a special value to denote an empty list
        return (value == null) ? "-" : value;
    }

    /**
      * Expand manager entry into String
     */
    public static String managerEntryToString(Hashtable entry)
            throws ValidationException {
        String value = null;
        if (entry.get(MANAGER_NAME) == null) {
            Thread.currentThread().dumpStack();
            Debug.println("Manager property " + MANAGER_NAME + " not found");

        }
        if (entry.get(MANAGER_PORT) == null) {
            Thread.currentThread().dumpStack();
            Debug.println("Manager property " + MANAGER_PORT + " not found");

        }
        if (entry.get(MANAGER_COMMUNITY) == null) {
            Thread.currentThread().dumpStack();
            Debug.println("Manager community " + MANAGER_COMMUNITY + " not found");

        }

        value = (String) entry.get(MANAGER_NAME) + "\t" +
                (String) entry.get(MANAGER_PORT) + "\t" +
                (String) entry.get(MANAGER_COMMUNITY);
        return value;
    }

    /**
      * CGI arguments used in getConfiguration()
     */
    public String getCGIParamsForGetOp() {
        return "op=getconfig";
    }

    /**
      * CGI arguments used in setConfiguration()
     */
    public String getCGIParamsForSetOp() {
        String result = "op=setconfig&" + toURLformat(_data);
        Debug.println("SNMPConfigData.getCGIParamsForSetOp=<" +
                result + ">");
        return result;
    }
}
