/** 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.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import com.netscape.management.client.util.*;
import com.netscape.management.client.console.ConsoleInfo;
import com.netscape.management.admserv.config.*;
import com.netscape.management.nmclf.SuiConstants;

/**
  *
  * @version 0.1 11/23/97
  * @author miodrag@netscape.com
  */
public class SNMPCommunityPanel extends PluginConfigPanel {

    IConfigDataModel _configData;

    static ResourceSet _resource;
    static String _i18nDescription, _i18nDetailsGroupbox;
    static String _i18nOperationsAll, _i18nOperationsGET,
    _i18nOperationsSET;
    static String _i18nDetailName, _i18nDetailOperations;
    static String _i18nEditDialogCommunity, _i18nEditDialogTitle,
    _i18nAddDialogTitle;
    static String _i18nMsgEnterCommunity, _i18nEditDialogOperationsGroupbox;

    static {
        _resource = new ResourceSet("com.netscape.management.admserv.panel.panel");
        _i18nDescription = _resource.getString("snmpcom","Description");
        _i18nDetailsGroupbox = _resource.getString("snmpcom","DetailsGroupbox");
        _i18nOperationsAll = _resource.getString("snmpcom","OperationsAll");
        _i18nOperationsGET = _resource.getString("snmpcom","OperationsGET");
        _i18nOperationsSET = _resource.getString("snmpcom","OperationsSET");
        _i18nDetailName = _resource.getString("snmpcom","DetailName");
        _i18nDetailOperations = _resource.getString("snmpcom","DetailOperations");
        _i18nEditDialogCommunity = _resource.getString("snmpcom","EditDialogCommunity");
        _i18nEditDialogTitle = _resource.getString("snmpcom","EditDialogTitle");
        _i18nAddDialogTitle = _resource.getString("snmpcom","AddDialogTitle");
        _i18nEditDialogOperationsGroupbox =
                _resource.getString("snmpcom","EditDialogOperationsGroupbox");
        _i18nMsgEnterCommunity = _resource.getString("snmpcom","MsgEnterCommunity");

    }

    Help _help;

    // Panel Controls
    JLabel _lblDescription;
    CommunityList _communityList;
    Vector _communities = new Vector();

    public SNMPCommunityPanel(String title, IConfigDataModel data) {
        super(title);
        _configData = data;

        setLayout(new BorderLayout());
        add(makePanel(), BorderLayout.NORTH);
        _help = new Help(_resource);
    }

    public void showHelp() {
        _help.contextHelp("SNMPCommunityHelp");
    }


    public void initialize() throws ConfigPanelException {
        setPanelContent(_configData);
    }

    public IConfigDataModel getDataModel() {
        return _configData;
    }

    public void setDataModel(IConfigDataModel data)
            throws ValidationException {
        _configData = data;
        if (_configData.isLoaded()) {
            setPanelContent(_configData);
        }
    }

    public void resetContent() throws ConfigPanelException {
        setPanelContent(_configData);
    }

    public void applyChanges() throws ValidationException {
        getPanelContent(_configData);
    }

    public void registerEditComponents(EditMonitor editMonitor) {
        _communityList.addListDataListener(editMonitor);
    }

    public void setPanelContent(IConfigDataModel data)
            throws ValidationException {
        String value = data.getAttribute(AttrNames.SNMP_COMMUNITIES);
        _communities = CGISNMPSetup.stringToCommunityVector(value);
        _communityList.setCommunities(_communities);
    }

    public void getPanelContent(IConfigDataModel data)
            throws ValidationException {
        String value = CGISNMPSetup.communityVectorToString(_communities);
        data.setAttribute(AttrNames.SNMP_COMMUNITIES, value);
    }

    /**
      *
     */
    protected JComponent makePanel() {
        JPanel p = new JPanel();
        GBC gbc = new GBC();
        GridBagLayout gbl;
        JPanel ctrlGroup;

        p.setLayout(gbl = new GridBagLayout());

        JLabel lbl = new JLabel(_i18nDescription);
        gbc.setInsets(10, 0, 10, 0);
        gbc.setGrid(0, 0, 1, 1);
        gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor
                GBC.HORIZONTAL); //fill
        p.add(lbl, gbc);

        _communityList = new CommunityList(_communities);
        //gbc.setInsets(topInset,leftColInset,0,0);
        gbc.setGrid(0, 1, 1, 1);
        gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor
                GBC.HORIZONTAL); //fill
        p.add(_communityList, gbc);

        return p;
    }
}

/**
  * A custom component that enables element in the list to be edited:
  * add, edit, remove
 */
class CommunityList extends EditableList {

    CommunityEditPanel _editPanel;
    JPanel _detailsPanel;
    JLabel _lblDetailsName, _lblDetailsOperation;
    Vector _communities;

    String _cmdSet = "SET", _cmdGet = "GET", _cmdAll = "ALL";

    static String _i18nEditCommunity, _i18nAddCommunity, _i18nRemoveCommunity;

    static {
        _i18nEditCommunity = _resource.getString("snmpcom","EditCommunityToolTip");
        _i18nAddCommunity = _resource.getString("snmpcom","AddCommunityToolTip");
        _i18nRemoveCommunity = _resource.getString("snmpcom","RemoveCommunityToolTip");    
    }

    public CommunityList(Vector communities) {
        setCommunities(communities);
    }

    public void setCommunities(Vector communities) {
        _communities = communities;
        setList(getCommunityNames(_communities));
    }

    Vector getCommunityNames(Vector entryList) {
        Vector v = new Vector(entryList.size());
        for (int i = 0; i < entryList.size(); i++) {
            Hashtable entry = (Hashtable) entryList.elementAt(i);
            v.addElement(entry.get(CGISNMPSetup.COMMUNITY_NAME));
        }
        return v;
    }

    public JPanel getEditPanel() {
        _editPanel = new CommunityEditPanel();
        JTextField[] txtComponents = _editPanel.getTextComponents();
        setEditPanelInitalFocusComponent(txtComponents[0]);
        setEditPanelCommitOnEnterComponents(txtComponents);
        return _editPanel;

    }

    public String getEditTitle() {
        return SNMPCommunityPanel._i18nEditDialogTitle;
    }

    public String getAddTitle() {
        return SNMPCommunityPanel._i18nAddDialogTitle;
    }

    public String getEditToolTip() {
        return _i18nEditCommunity;
    }

    public String getAddToolTip() {
        return _i18nAddCommunity;
    }

    public String getRemoveToolTip() {
        return _i18nRemoveCommunity;
    }

    public ResourceSet getHelpResourceSet() {
        return SNMPCommunityPanel._resource;
    };
    public String getHelpToken() {
        return "editSNMPCommunityHelp";
    }


    public JPanel getDetailsPanel() {
        return _detailsPanel = createDetailsPanel();
    }

    public String getDetailsTitle() {
        return SNMPCommunityPanel._i18nDetailsGroupbox;
    }


    private JPanel createDetailsPanel() {
        JPanel p = new JPanel(new GridBagLayout());
        GBC gbc = new GBC();

        JLabel lbl = new JLabel(SNMPCommunityPanel._i18nDetailName,
                JLabel.LEFT);
        //lbl.setFont(BaseConfigPanel.getLabelFont());
        gbc.setInsets(0, 0, 0, 0);
        gbc.setGrid(0, 0, 1, 1);
        gbc.setSpace(0.0, 0.0, GBC.NORTHWEST, // anchor
                GBC.BOTH); //fill
        p.add(lbl, gbc);

        _lblDetailsName = new JLabel(" ", JLabel.LEFT);
        gbc.setInsets(0, 10, 0, 0);
        gbc.setGrid(1, 0, 1, 1);
        gbc.setSpace(1.0, 0.0, GBC.NORTHWEST, // anchor
                GBC.HORIZONTAL); //fill
        p.add(_lblDetailsName, gbc);

        lbl = new JLabel(SNMPCommunityPanel._i18nDetailOperations,
                JLabel.LEFT);
        //lbl.setFont(BaseConfigPanel.getLabelFont());
        gbc.setInsets(10, 0, 0, 0);
        gbc.setGrid(0, 1, 1, 1);
        gbc.setSpace(0.0, 0.0, GBC.NORTHWEST, // anchor
                GBC.HORIZONTAL); //fill
        p.add(lbl, gbc);

        _lblDetailsOperation = new JLabel(" ", JLabel.LEFT);
        gbc.setInsets(10, 10, 0, 0);
        gbc.setGrid(1, 1, 1, 1);
        gbc.setSpace(1.0, 0.0, GBC.NORTHWEST, // anchor
                GBC.HORIZONTAL); //fill
        p.add(_lblDetailsOperation, gbc);

        return p;

    }

    public void validateEdit() throws ValidationException {
        String community = _editPanel.getCommunity();
        if (community.length() == 0) {
            throw new ValidationException(
                    SNMPCommunityPanel._i18nEditDialogCommunity,
                    SNMPCommunityPanel._i18nMsgEnterCommunity);
        }
    }

    public void setEditPanelParameters(String item) {
        if (item == null) { //add
            _editPanel.setCommunity("");
            _editPanel.setOperation(_cmdAll);
        } else { //edit
            int idx = findCommunity(item);
            if (idx >= 0) {
                Hashtable entry = (Hashtable)_communities.elementAt(idx);
                _editPanel.setCommunity(item);
                _editPanel.setOperation( (String) entry.get(
                        CGISNMPSetup.COMMUNITY_OPERATION));
            } else {
                Debug.println("ERROR: Community not found: " + item);
            }
        }
    }

    public String getEditPanelItem() {
        return _editPanel.getCommunity();
    }


    private int findCommunity(String name) {
        return CGISNMPSetup.findEntry(_communities,
                CGISNMPSetup.COMMUNITY_NAME , name);
    }

    public void createItem(String item) {
        _communities.addElement(
                CGISNMPSetup.createCommunityEntry(new String(item),
                new String(_editPanel.getOperation())));
        //dumpData();
    }

    public void removeItem(String item) {
        int idx = findCommunity(item);
        if (idx >= 0) {
            _communities.removeElementAt(idx);
        } else {
            Debug.println("ERROR: Community not found: " + item);
        }
        //dumpData();
    }

    public void updateItem(String item, boolean isRenamed) {
        int idx = findCommunity(item);
        if (idx >= 0) {
            Hashtable entry = CGISNMPSetup.createCommunityEntry(
                    new String(_editPanel.getCommunity()),
                    new String(_editPanel.getOperation()));
            _communities.setElementAt(entry, idx);
        } else {
            Debug.println("ERROR: Community not found: " + item);
        }
        //dumpData();
    }


    private void dumpData() {
        if (_communities.size() == 0) {
            Debug.println("No entries");
            return;
        }

        for (int i = 0; i < _communities.size(); i++) {
            Hashtable entry = (Hashtable)_communities.elementAt(i);
            String community =
                    (String) entry.get(CGISNMPSetup.COMMUNITY_NAME);
            String operation =
                    (String) entry.get(CGISNMPSetup.COMMUNITY_OPERATION);
            Debug.print(i + "=[" + community + " " + operation + "] ");
        }
        Debug.println("");
    }


    public void selectItem(String item) {

        //Debug.println("selectItem " + item);

        if (item == null) {
            _lblDetailsName.setText("");
            _lblDetailsOperation.setText("");
            return;
        }

        int idx = findCommunity(item);

        if (idx >= 0) {

            Hashtable entry = (Hashtable)_communities.elementAt(idx);
            String community =
                    (String) entry.get(CGISNMPSetup.COMMUNITY_NAME);
            String operation =
                    (String) entry.get(CGISNMPSetup.COMMUNITY_OPERATION);

            //Debug.println("idx=" + idx + " detail =" + name + " " + operation);

            _lblDetailsName.setText(community);

            if (operation.equals(_cmdAll)) {
                operation = SNMPCommunityPanel._i18nOperationsAll;
            } else if (operation.equals(_cmdGet)) {
                operation = SNMPCommunityPanel._i18nOperationsGET;
            } else if (operation.equals(_cmdSet)) {
                operation = SNMPCommunityPanel._i18nOperationsSET;
            } else {
                Debug.println("ERROR: Bad perrmissions: " + item);
            }
            _lblDetailsOperation.setText(operation);
        } else {
            Thread.currentThread().dumpStack();
            Debug.println("ERROR: Community not found: " + item);
        }
    }

}

/**
  * Community Edit Dialog
 */
class CommunityEditPanel extends JPanel implements SuiConstants {
    String _community = "";
    JTextField _txtCommunity;
    JRadioButton _rbSet, _rbGet, _rbAll;
    String _cmdSet = "SET", _cmdGet = "GET", _cmdAll = "ALL";

    String _operation = _cmdAll;

    public CommunityEditPanel() {
        createLayout();
    }

    private Border createGroupBorder(String label) {
        TitledBorder border = new TitledBorder(new EtchedBorder(), label);
        border.setTitleFont(BaseConfigPanel.getLabelFont());
        return new CompoundBorder(border, new EmptyBorder(0, 6, 0, 0));

    }

    private void createLayout() {
        GBC gbc = new GBC();
        setLayout(new GridBagLayout());

        JLabel lblCommunity =
                new JLabel(SNMPCommunityPanel._i18nEditDialogCommunity);
        lblCommunity.setFont(BaseConfigPanel.getLabelFont());
        gbc.setInsets(COMPONENT_SPACE, 0, 0, 0);
        gbc.setGrid(0, 0, 1, 1);
        gbc.setSpace(0.0, 0.0, GBC.EAST, // anchor
                GBC.NONE); //fill
        add(lblCommunity, gbc);

        _txtCommunity = new JTextField(_community, 16);
        gbc.setInsets(COMPONENT_SPACE, DIFFERENT_COMPONENT_SPACE, 0, 0);
        gbc.setGrid(1, 0, 1, 1);
        gbc.setSpace(1.0, 0.0, GBC.NORTHWEST, //anchor
                GBC.HORIZONTAL); //fill
        add(_txtCommunity, gbc);
        lblCommunity.setLabelFor(_txtCommunity);

        JPanel operationPanel = new JPanel(new GridLayout(1, 0, 0, 5));
        operationPanel.setBorder( createGroupBorder(
                SNMPCommunityPanel._i18nEditDialogOperationsGroupbox));
        ButtonGroup radio = new ButtonGroup();

        _rbAll = new JRadioButton(SNMPCommunityPanel._i18nOperationsAll);
        _rbAll.setActionCommand(_cmdAll);
        _rbAll.addActionListener(radioListener);
        _rbAll.setSelected(true);
        radio.add(_rbAll);
        operationPanel.add(_rbAll);

        _rbGet = new JRadioButton(SNMPCommunityPanel._i18nOperationsGET);
        _rbGet.setActionCommand(_cmdGet);
        _rbGet.addActionListener(radioListener);
        radio.add(_rbGet);
        operationPanel.add(_rbGet);

        _rbSet = new JRadioButton(SNMPCommunityPanel._i18nOperationsSET);
        _rbSet.setActionCommand(_cmdSet);
        _rbSet.addActionListener(radioListener);
        radio.add(_rbSet);
        operationPanel.add(_rbSet);

        gbc.setInsets(COMPONENT_SPACE, 0, 0, 0);
        gbc.setGrid(0, 1, 2, 1);
        gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor
                GBC.HORIZONTAL); //fill
        add(operationPanel, gbc);

    }

    private ActionListener radioListener = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    _operation = e.getActionCommand();
                }
            };

    public String getCommunity() {
        return _community = _txtCommunity.getText().trim();
    }

    public void setCommunity(String community) {
        _txtCommunity.setText(_community = community);
    }

    public String getOperation() {
        return _operation;
    }

    public void setOperation(String operation) {
        _operation = operation;
        if (operation.equals(_cmdAll)) {
            _rbAll.setSelected(true);
        } else if (operation.equals(_cmdGet)) {
            _rbGet.setSelected(true);
        } else if (operation.equals(_cmdSet)) {
            _rbSet.setSelected(true);
        } else {
            Thread.currentThread().dumpStack();
            Debug.println("ERROR: Bad operation selector <" +
                    operation + ">");
            _rbAll.setSelected(true);
            _operation = _cmdAll;
        }
    }

    public JTextField[] getTextComponents() {
        return new JTextField[]{ _txtCommunity };
    }
}
