/** 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 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 SNMPManagerPanel extends PluginConfigPanel {

    IConfigDataModel _configData;

    static ResourceSet _resource;
    static String _i18nDescription, _i18nEditDialogTitle,
    _i18nAddDialogTitle;
    static String _i18nManager, _i18nPort, _i18nCommunity,
    _i18nDetailsGroupbox;
    static String _i18nMsgEnterManager, _i18nMsgEntryExists,
    _i18nMsgCanNotRename;

    static {
        _resource = new ResourceSet("com.netscape.management.admserv.panel.panel");
        _i18nDescription = _resource.getString("snmpmgr","Description");
        _i18nEditDialogTitle = _resource.getString("snmpmgr","EditDialogTitle");
        _i18nAddDialogTitle = _resource.getString("snmpmgr","AddDialogTitle");
        _i18nManager = _resource.getString("snmpmgr","Manager");
        _i18nPort = _resource.getString("snmpmgr","Port");
        _i18nCommunity = _resource.getString("snmpmgr","Community");
        _i18nDetailsGroupbox = _resource.getString("snmpmgr","DetailsGroupbox");
        _i18nMsgEnterManager = _resource.getString("snmpmgr","MsgEnterManager");
        _i18nMsgEntryExists = _resource.getString("snmpmgr","MsgEntryExists");
        _i18nMsgCanNotRename = _resource.getString("snmpmgr","MsgCanNotRename");
    }

    Help _help;

    // Panel Controls
    JLabel _lblDescription;
    ManagerList _managerList;
    Vector _managers = new Vector();

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

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

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


    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) {
        _managerList.addListDataListener(editMonitor);
    }

    public void setPanelContent(IConfigDataModel data)
            throws ValidationException {
        String value = data.getAttribute(AttrNames.SNMP_MANAGERS);
        _managers = CGISNMPSetup.stringToManagerVector(value);
        _managerList.setManagers(_managers);
    }

    public void getPanelContent(IConfigDataModel data)
            throws ValidationException {
        String value = CGISNMPSetup.managerVectorToString(_managers);
        Debug.println("managers value = <" + value + ">");
        data.setAttribute(AttrNames.SNMP_MANAGERS, 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);

        _managerList = new ManagerList(_managers);
        //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(_managerList, gbc);

        return p;
    }
}

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

    ManagerEditPanel _editPanel;
    JPanel _detailsPanel;
    JLabel _lblDetailsManager, _lblDetailsPort, _lblDetailsCommunity;
    Vector _managers;
    int _editEntryIdx = -1;

    static String _i18nEditMgr, _i18nAddMgr, _i18nRemoveMgr;

    static {
        _i18nEditMgr = _resource.getString("snmpmgr","EditMgrToolTip");
        _i18nAddMgr = _resource.getString("snmpmgr","AddMgrToolTip");
        _i18nRemoveMgr = _resource.getString("snmpmgr","RemoveMgrToolTip");
    }

    public ManagerList(Vector managers) {
        setManagers(managers);
    }

    public void setManagers(Vector managers) {
        _managers = managers;
        setList(getManagerNames(_managers));
    }

    Vector getManagerNames(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.MANAGER_NAME));
        }
        return v;
    }

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

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

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

    public String getEditToolTip() {
        return _i18nEditMgr;
    }

    public String getAddToolTip() {
        return _i18nAddMgr;
    }

    public String getRemoveToolTip() {
        return _i18nRemoveMgr;
    }

    public ResourceSet getHelpResourceSet() {
        return SNMPManagerPanel._resource;
    };
    public String getHelpToken() {
        return "editSNMPManagerHelp";
    }

    public void validateEdit() throws ValidationException {
        String manager = _editPanel.getManager();
        if (manager.length() == 0) {
            throw new ValidationException( SNMPManagerPanel._i18nManager,
                    SNMPManagerPanel._i18nMsgEnterManager);
        }
        int idx = findManager(manager);
        if (idx >= 0) {
            if (_editEntryIdx == -1) { // create new entry in progress
                throw new ValidationException(
                        SNMPManagerPanel._i18nManager,
                        SNMPManagerPanel._i18nMsgEntryExists);
            } else if (idx != _editEntryIdx) {
                throw new ValidationException(
                        SNMPManagerPanel._i18nManager,
                        SNMPManagerPanel._i18nMsgCanNotRename);
            }
        }
    }

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

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

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

        JLabel lbl = new JLabel(SNMPManagerPanel._i18nManager);
        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);

        _lblDetailsManager = new JLabel(" ");
        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(_lblDetailsManager, gbc);

        lbl = new JLabel(SNMPManagerPanel._i18nPort);
        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);

        _lblDetailsPort = new JLabel(" ");
        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(_lblDetailsPort, gbc);

        lbl = new JLabel(SNMPManagerPanel._i18nCommunity);
        gbc.setInsets(10, 0, 0, 0);
        gbc.setGrid(0, 2, 1, 1);
        gbc.setSpace(0.0, 0.0, GBC.NORTHWEST, // anchor
                GBC.HORIZONTAL); //fill
        p.add(lbl, gbc);

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

        return p;

    }

    public void setEditPanelParameters(String item) {
        if (item == null) { //add
            _editPanel.setCommunity("public");
            _editPanel.setPort("162");
            _editPanel.setManager("");
            _editEntryIdx = -1;
        } else { //edit
            int idx = findManager(item);
            if (idx >= 0) {
                _editEntryIdx = idx;

                Hashtable entry = (Hashtable)_managers.elementAt(idx);
                String manager =
                        (String) entry.get(CGISNMPSetup.MANAGER_NAME);
                String port = (String) entry.get(CGISNMPSetup.MANAGER_PORT);
                String community = (String) entry.get(
                        CGISNMPSetup.MANAGER_COMMUNITY);

                _editPanel.setManager(manager);
                _editPanel.setPort(port);
                _editPanel.setCommunity(community);
            } else {
                Debug.println("ERROR: Manager not found: " + item);
            }
        }
    }

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


    private int findManager(String name) {
        return CGISNMPSetup.findEntry(_managers,
                CGISNMPSetup.MANAGER_NAME , name);
    }

    public void createItem(String item) {
        _managers.addElement(
                CGISNMPSetup.createManagerEntry(new String(item),
                new String(_editPanel.getPort()),
                new String(_editPanel.getCommunity())));
        //dumpData();
    }

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

    public void updateItem(String item, boolean isRenamed) {
        int idx = findManager(item);
        if (idx >= 0) {
            Hashtable entry = CGISNMPSetup.createManagerEntry(
                    new String(_editPanel.getManager()),
                    new String(_editPanel.getPort()),
                    new String(_editPanel.getCommunity()));

            _managers.setElementAt(entry, idx);
        } else {
            Debug.println("ERROR: Manager not found: " + item);
        }
        //dumpData();
    }


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

        for (int i = 0; i < _managers.size(); i++) {
            Hashtable entry = (Hashtable)_managers.elementAt(i);
            String manager = (String) entry.get(CGISNMPSetup.MANAGER_NAME);
            String port = (String) entry.get(CGISNMPSetup.MANAGER_PORT);
            String community =
                    (String) entry.get(CGISNMPSetup.MANAGER_COMMUNITY);
            Debug.print(i + "=[" + manager + " " + port + " " +
                    community + "] ");
        }
        Debug.println("");
    }

    public void selectItem(String item) {

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

        if (item == null) {
            _lblDetailsManager.setText("");
            _lblDetailsPort.setText("");
            _lblDetailsCommunity.setText("");
            return;
        }

        int idx = findManager(item);

        if (idx >= 0) {
            Hashtable entry = (Hashtable)_managers.elementAt(idx);
            String manager = (String) entry.get(CGISNMPSetup.MANAGER_NAME);
            String port = (String) entry.get(CGISNMPSetup.MANAGER_PORT);
            String community =
                    (String) entry.get(CGISNMPSetup.MANAGER_COMMUNITY);

            _lblDetailsManager.setText(manager);
            _lblDetailsPort.setText(port);
            _lblDetailsCommunity.setText(community);
        } else {
            Debug.println("ERROR: Manager not found: " + item);
        }
    }

}

/**
  * Manager Edit Dialog
 */
class ManagerEditPanel extends JPanel implements SuiConstants {
    String _manager = "", _port = "", _community = "";
    JTextField _txtManager, _txtPort, _txtCommunity;

    public ManagerEditPanel() {
        createLayout();
    }

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

        JLabel lblManager = new JLabel(SNMPManagerPanel._i18nManager);
        lblManager.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(lblManager, gbc);

        _txtManager = new JTextField(_manager, 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(_txtManager, gbc);
        lblManager.setLabelFor(_txtManager);

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

        _txtPort = new JTextField(_port, 6);
        _txtPort.setDocument(FilteredInputDocument.allowDigitsOnly());
        gbc.setInsets(COMPONENT_SPACE, DIFFERENT_COMPONENT_SPACE, 0, 0);
        gbc.setGrid(1, 1, 1, 1);
        gbc.setSpace(1.0, 0.0, GBC.NORTHWEST, //anchor
                GBC.NONE); //fill
        add(_txtPort, gbc);
        lblPort.setLabelFor(_txtPort);

        JLabel lblCommunity = new JLabel(SNMPManagerPanel._i18nCommunity);
        lblCommunity.setFont(BaseConfigPanel.getLabelFont());
        gbc.setInsets(COMPONENT_SPACE, 0, 0, 0);
        gbc.setGrid(0, 2, 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, 2, 1, 1);
        gbc.setSpace(1.0, 0.0, GBC.NORTHWEST, //anchor
                GBC.HORIZONTAL); //fill
        add(_txtCommunity, gbc);
        lblCommunity.setLabelFor(_txtCommunity);
    }

    public String getManager() {
        return _manager = _txtManager.getText().trim();
    }

    public void setManager(String manager) {
        _txtManager.setText(_manager = manager);
    }

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

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

    public String getPort() {
        return _port = _txtPort.getText().trim();
    }

    public void setPort(String port) {
        _txtPort.setText(_port = port);
    }

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