/*
 * NetworkBasicView.java
 * 
 * Copyright (c) 2003-2004 Digi International
 * This program and the information contained in it is confidential and
 * proprietary to Digi International and may not be used, copied, or re-
 * produced without the prior written permission of Digi International.
 * 
 */

package com.digi.config.ui;

import com.digi.config.core.*;
import com.digi.config.util.*;

import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.net.*;




/** 
 * This class is a view panel that shows basic network
 * informational panel for the ConnectMe device
 * 
 * This view can be embedded in other panels as desired.
 */


public class NetworkWirelessSecurityView extends ConfigViewImpl {
    /** A KvpNode that holds just the kvpGroup used in this view */
    KvpNode viewSettingTree;
    /** listens to the device for changes to kvpGroup */
    DeviceChangeListener settingChangeListener;
    /** Panel that holds the view content */
    GridContentPanel content;

    // Data Fields currently used in this view
    KvpField wlanWEPModeKvpField;
    KvpField wlanWEPTransmitKeyKvpField;
    KvpField wlanWEPKeyKvpField[] = new KvpField[4];
    KvpField wlanSecurityKvpField;

    // UI Controls for each field
    JComboBox    wlanWEPMode_UIC;
    JRadioButton wlanWEPTransmitKey_UIC[] = new JRadioButton[4];
    JTextField   wlanWEPKey_UIC[] = new JTextField[4];

    /**
     * Constructor. Sets up the view controls
     */
    public NetworkWirelessSecurityView() throws Exception {
        // create the KvpNode and the kvpGroup change listener
        viewSettingTree = new KvpNode();
        settingChangeListener = new DeviceChangeListener() {
            public void deviceChanged(DeviceChangeEvent e) {
                //SystemLog.debug("NetworkBasicView was notified that device kvpGroup changed");
                refreshViewData();
                refreshViewControls();
            }
        };
        // Create the panel that will hold the view controls
        content = new GridContentPanel(this.getName(),5);
        // create a listener that will detect when a user edits the field values
        ControlChangeAdapter fieldListener = new ControlChangeAdapter() {
            public void changePerformed(Object source, ActionEvent ae, FocusEvent fe) {
                //SystemLog.debug("NetworkWirelessSecurityView was notified that field "+source.toString()+" changed.");
                if (source==wlanWEPMode_UIC) {
                    if (wlanWEPMode_UIC.getSelectedIndex() == 0) {
                        wlanSecurityKvpField.setStringValue(new String("open"));
                    }
                    else {
                        wlanSecurityKvpField.setStringValue(new String("wep"));
                        wlanWEPModeKvpField.setStringValue(wlanWEPMode_UIC.getSelectedItem().toString());
                    }
                } else if (source==wlanWEPTransmitKey_UIC[0]) {
                    wlanWEPTransmitKeyKvpField.setStringValue("1");
                } else if (source==wlanWEPTransmitKey_UIC[1]) {
                    wlanWEPTransmitKeyKvpField.setStringValue("2");
                } else if (source==wlanWEPTransmitKey_UIC[2]) {
                    wlanWEPTransmitKeyKvpField.setStringValue("3");
                } else if (source==wlanWEPTransmitKey_UIC[3]) {
                    wlanWEPTransmitKeyKvpField.setStringValue("4");
                } else if (source==wlanWEPKey_UIC[0]) {
                    wlanWEPKeyKvpField[0].setStringValue(wlanWEPKey_UIC[0].getText());
                } else if (source==wlanWEPKey_UIC[1]) {
                    wlanWEPKeyKvpField[1].setStringValue(wlanWEPKey_UIC[1].getText());
                } else if (source==wlanWEPKey_UIC[2]) {
                    wlanWEPKeyKvpField[2].setStringValue(wlanWEPKey_UIC[2].getText());
                } else if (source==wlanWEPKey_UIC[3]) {
                    wlanWEPKeyKvpField[3].setStringValue(wlanWEPKey_UIC[3].getText());
                }
            }
        };

        //
        // Create the fields and put them on the view
        //


        String wlanWEPModeChoices[] = { "Open (None)", "64bit", "128bit" };
        wlanWEPMode_UIC = content.addJComboBox("WLANWepMode", "WLANWepModeDesc", wlanWEPModeChoices, fieldListener);

        ButtonGroup wlanWEPKeyGroup = new ButtonGroup();
        content.addJLabel("WLANWepTransmitKey", null, 0, 0, false);
        wlanWEPTransmitKey_UIC[0] = content.addJRadioButton("1", fieldListener, wlanWEPKeyGroup, 1, false);
        wlanWEPTransmitKey_UIC[1] = content.addJRadioButton("2", fieldListener, wlanWEPKeyGroup, 2, false);
        wlanWEPTransmitKey_UIC[2] = content.addJRadioButton("3", fieldListener, wlanWEPKeyGroup, 3, false);
        wlanWEPTransmitKey_UIC[3] = content.addJRadioButton("4", fieldListener, wlanWEPKeyGroup, 4, true);

        content.addBlankLine();
        content.addTextLine("WLANWepEncryptionKeys");

        wlanWEPKey_UIC[0] = content.addJTextField("1:", "", 100, fieldListener);
        wlanWEPKey_UIC[1] = content.addJTextField("2:", "", 100, fieldListener);
        wlanWEPKey_UIC[2] = content.addJTextField("3:", "", 100, fieldListener);
        wlanWEPKey_UIC[3] = content.addJTextField("4:", "", 100, fieldListener);
        
        content.addVGlue();
    }

    /**
     * Returns a one word name identifying this view. 
     */
    public String getName() {
        return "NetworkWirelessSecurityView";
    }

    /** 
     * Return the Component that displays the primary content for this view
     */
    public Component getViewContent() {
        return content;
    }

    /**
     * Informs view what device to work with. View should flush any
     * cached device data and mark current view content as invalid
     * so that it is refreshed appropriatly.
     */
    public void setDevice(Device newDevice) {
        super.setDevice(newDevice);
        refreshViewData();
        refreshViewControls();
        device.addSettingChangeListener(settingChangeListener);
    }

    /** 
     * Refreshes the local copy of the kvpGroup displayed in the view. The updated kvpGroup come
     * from those currently cached in the Device
     */
    private void refreshViewData() {
        viewSettingTree.clear();

        KvpNode wlanWepKeys = new KvpNode("boot");
        wlanWepKeys.mergeChild(new KvpNode("wepkey1"));
        wlanWepKeys.mergeChild(new KvpNode("wepkey2"));
        wlanWepKeys.mergeChild(new KvpNode("wepkey3"));
        wlanWepKeys.mergeChild(new KvpNode("wepkey4"));
        viewSettingTree.mergeChild(wlanWepKeys);

        wlanWEPModeKvpField = viewSettingTree.mergeFrom(device.getInternalSettingTree(), "boot", "wep_type");
        wlanWEPTransmitKeyKvpField = viewSettingTree.mergeFrom(device.getInternalSettingTree(), "boot", "wepkey_index");
        wlanSecurityKvpField = viewSettingTree.mergeFrom(device.getInternalSettingTree(), "boot", "security");
        wlanWEPKeyKvpField[0] = viewSettingTree.getField("boot", "wepkey1");
        wlanWEPKeyKvpField[1] = viewSettingTree.getField("boot", "wepkey2");
        wlanWEPKeyKvpField[2] = viewSettingTree.getField("boot", "wepkey3");
        wlanWEPKeyKvpField[3] = viewSettingTree.getField("boot", "wepkey4");
    }

    /** 
     * Refreshes the state of the controls in the view to match the data in the views kvpGroup.
     */
    private void refreshViewControls() {
        wlanWEPMode_UIC.setEnabled(wlanWEPModeKvpField!=null);
        if (wlanWEPModeKvpField!=null) {
            if (wlanSecurityKvpField!=null && wlanSecurityKvpField.getStringValue().compareTo(new String("wep")) == 0)
                wlanWEPMode_UIC.setSelectedItem(wlanWEPModeKvpField.getStringValue());
            else wlanWEPMode_UIC.setSelectedIndex(0);
        }
        wlanWEPTransmitKey_UIC[0].setEnabled(wlanWEPTransmitKeyKvpField!=null);
        wlanWEPTransmitKey_UIC[1].setEnabled(wlanWEPTransmitKeyKvpField!=null);
        wlanWEPTransmitKey_UIC[2].setEnabled(wlanWEPTransmitKeyKvpField!=null);
        wlanWEPTransmitKey_UIC[3].setEnabled(wlanWEPTransmitKeyKvpField!=null);
        if (wlanWEPTransmitKeyKvpField!=null) {
            int value = new Integer(wlanWEPTransmitKeyKvpField.getStringValue()).intValue();
            wlanWEPTransmitKey_UIC[0].setSelected(value == 1 ? true : false);
            wlanWEPTransmitKey_UIC[1].setSelected(value == 2 ? true : false);
            wlanWEPTransmitKey_UIC[2].setSelected(value == 3 ? true : false);
            wlanWEPTransmitKey_UIC[3].setSelected(value == 4 ? true : false);
        }

        for (int i = 0; i < 4; i++) {
            wlanWEPKey_UIC[i].setEnabled(wlanWEPKeyKvpField[i]!=null);
            if (wlanWEPKeyKvpField[i]!=null) {
                wlanWEPKey_UIC[i].setText(wlanWEPKeyKvpField[i].getStringValue());
            }
        }
        // If no device data is not available, disable the entire panel
        if (wlanWEPModeKvpField==null) {
            content.setContainerEnabled(false);
        }

    }

    /**
     * This method is called to instruct the view that it is about to be made
     * active. When a view is active it needs to make sure its content is correct.
     * An example of why a panel may be inactive is if it were on a tabbed pane 
     * and was not currently visible or if the user selected some other view.
     */
    public void activate() {
        SystemLog.debug("Activating "+getName());
    }

    /**
     * This method is called to instruct the view that it is about to be made
     * inactive. When a view is inactive, it does not need to worry
     * about maintaining its content in a correct state. An example of why a panel
     * may be inactive is if it were on a tabbed pane and was not currently visible
     * or if the user selected some other view.
     */
    public void deactivate() {
        SystemLog.debug("Deactivating "+getName());
    }

    /**
     * Indicates if any changes have been made by the user that have not yet been
     * saved to the device(ie committed).
     */
    public boolean isChanged() {
        return viewSettingTree.hasChanged();
    }

    /**
     * This method instructs the view to validate any of the changes the user has made
     * within the view. Any errors are to be added to the provided errorList. 
     * 
     * @param errorList is a collection of ViewValidationError objects
     */
    public void validateChanges(Collection errorList) {
        try {
            // Nothing to Verify
        } catch (Exception e) {
            System.out.println("Caught Exception in NetworkWirelessSecurityView::validationChanges()");
            e.printStackTrace();
        }
    }

    /**
     * This method instructs the view to place any changes the user has made within 
     * the view into the provided cluster. Once the changes have been saved to
     * to the device, a subsequent call to commitChanges() will be made.
     */
    public void getChanges(KvpNode settingCluster, KvpNode stateCluster) {
        // Merge the view changes into the provided cluster
        settingCluster.merge(viewSettingTree, false);
    }

    /**
     * Instructs the view to consider any user changes within the view as 
     * saved to the device (ie committed).
     */
    public void commitChanges() {
        // simply reset flags indicating user changes in the contols
        viewSettingTree.resetChanged();
    }

    /** 
     * Instructs the view to discard any changes the user has made within the
     * view and revert those fields to the original state. The view is also 
     * free to refresh all its fields to the present cached state of the device at 
     * this time.
     */
    public void cancelChanges() {
        refreshViewData();
        refreshViewControls();
    }


}

