/*
 * 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 wireless
 * informational panel for the ConnectMe device
 * 
 * This view can be embedded in other panels as desired.
 */


public class NetworkWirelessView 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;
    /** Subpanel holding the SSID content */
    GridContentPanel wlanSSIDContent;

    // Data Fields currently used in this view
    KvpField wlanModeKvpField;
    KvpField wlanSSIDKvpField;
    KvpField wlanCountryKvpField;
    KvpField wlanChannelKvpField;

    // UI Controls for each field
    JRadioButton wlanModeInfrastructure_UIC;
    JRadioButton wlanModeAdHoc_UIC;
    JRadioButton wlanAutoSSID_UIC;
    JRadioButton wlanManualSSID_UIC;
    JTextField wlanSSID_UIC;
    JComboBox wlanCountry_UIC;
    JComboBox wlanChannel_UIC;

    /**
     * Constructor. Sets up the view controls
     */
    public NetworkWirelessView() 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(),1);
        // 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("NetworkWirelessView was notified that field "+source.toString()+" changed.");
                if ((source==wlanModeInfrastructure_UIC) || (source==wlanModeAdHoc_UIC)) {
                    if (wlanModeInfrastructure_UIC.isSelected())
                        wlanModeKvpField.setStringValue("bss_join");
                    else if (wlanModeAdHoc_UIC.isSelected())
                        wlanModeKvpField.setStringValue("ibss_join_create");
                } else if ((source==wlanAutoSSID_UIC) || (source==wlanManualSSID_UIC)) {
                    if (wlanAutoSSID_UIC.isSelected())
                        wlanSSIDKvpField.setStringValue("");
                    else if (wlanManualSSID_UIC.isSelected())
                        wlanSSIDKvpField.setStringValue(wlanSSID_UIC.getText());
                    wlanSSIDContent.setContainerEnabled(wlanManualSSID_UIC.isSelected());
                } else if (source==wlanSSID_UIC) {
                    wlanSSIDKvpField.setStringValue(wlanSSID_UIC.getText());
                } else if (source==wlanCountry_UIC) {
                    wlanCountryKvpField.setStringValue(wlanCountry_UIC.getSelectedItem().toString());
                } else if (source==wlanChannel_UIC) {
                    if (wlanChannel_UIC.getSelectedIndex() == 0)
                        wlanChannelKvpField.setStringValue(new String("0"));
                    else wlanChannelKvpField.setStringValue(wlanChannel_UIC.getSelectedItem().toString());
                }
            }
        };

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

        content.addTextLine("WLANConnectMethod");
        
        ButtonGroup wlanModeGroup = new ButtonGroup();
        wlanModeInfrastructure_UIC = content.addJRadioButton("WLANModeInfrastructure", fieldListener);
        wlanModeGroup.add(wlanModeInfrastructure_UIC);
        wlanModeAdHoc_UIC = content.addJRadioButton("WLANModeAdHoc", fieldListener);
        wlanModeGroup.add(wlanModeAdHoc_UIC);

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

        ButtonGroup wlanSSIDGroup = new ButtonGroup();
        wlanAutoSSID_UIC = content.addJRadioButton("WLANAutoSSID", fieldListener);
        wlanSSIDGroup.add(wlanAutoSSID_UIC);
        wlanManualSSID_UIC = content.addJRadioButton("WLANManualSSID", fieldListener);
        wlanSSIDGroup.add(wlanManualSSID_UIC);

        // Create the panel that will hold the SSID controls
        wlanSSIDContent = new GridContentPanel(1);
        wlanSSID_UIC = wlanSSIDContent.addJTextField("WLAN_SSID", "WLAN_SSIDDesc", 100, fieldListener);

        content.addSubPanel(wlanSSIDContent);
        content.addBlankLine();

        String wlanCountryChoices[] = {"United States", "Canada"};
        wlanCountry_UIC = content.addJComboBox("WLANCountry", "WLANCountryDesc", wlanCountryChoices, fieldListener);

        String wlanChannelChoices[] = {"Auto-Scan", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14" };
        wlanChannel_UIC = content.addJComboBox("WLANChannel", "WLANChannelDesc", wlanChannelChoices, fieldListener);

        content.addVGlue();
    }

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

    /** 
     * 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();
        wlanModeKvpField = viewSettingTree.mergeFrom(device.getInternalSettingTree(), "boot", "protocol_mode");
        wlanSSIDKvpField = viewSettingTree.mergeFrom(device.getInternalSettingTree(), "boot", "ssid");
        wlanCountryKvpField = viewSettingTree.mergeFrom(device.getInternalSettingTree(), "boot", "country_code");
        wlanChannelKvpField = viewSettingTree.mergeFrom(device.getInternalSettingTree(), "boot", "channel");
    }

    /** 
     * Refreshes the state of the controls in the view to match the data in the views kvpGroup.
     */
    private void refreshViewControls() {
        wlanSSID_UIC.setEnabled(wlanSSIDKvpField!=null);
        if (wlanSSIDKvpField!=null) {
            wlanSSID_UIC.setText(wlanSSIDKvpField.getStringValue());
        }

        wlanModeInfrastructure_UIC.setEnabled(wlanModeKvpField!=null);
        wlanModeAdHoc_UIC.setEnabled(wlanModeKvpField!=null);
        if (wlanModeKvpField!=null) {
            boolean infrastructureEnabled = (wlanModeKvpField.getStringValue().compareTo(new String("bss_join")) == 0 ? true : false);
            wlanModeInfrastructure_UIC.setSelected(infrastructureEnabled);
            wlanModeAdHoc_UIC.setSelected(!infrastructureEnabled);
        }

        wlanAutoSSID_UIC.setEnabled(wlanSSIDKvpField!=null);
        wlanManualSSID_UIC.setEnabled(wlanSSIDKvpField!=null);
        if (wlanSSIDKvpField!=null) {
            boolean autoEnabled = (wlanSSIDKvpField.getStringValue().length() == 0 ? true : false);
            wlanAutoSSID_UIC.setSelected(autoEnabled);
            wlanManualSSID_UIC.setSelected(!autoEnabled);
            wlanSSIDContent.setContainerEnabled(!autoEnabled);
        }

        wlanCountry_UIC.setEnabled(wlanCountryKvpField!=null);
        if (wlanCountryKvpField!=null) {
            wlanCountry_UIC.setSelectedItem(wlanCountryKvpField.getStringValue());
        }

        wlanChannel_UIC.setEnabled(wlanChannelKvpField!=null);
        if (wlanChannelKvpField!=null) {
            if (new Integer(wlanChannelKvpField.getStringValue()).intValue() == 0)
                wlanChannel_UIC.setSelectedIndex(0);
            else wlanChannel_UIC.setSelectedItem(wlanChannelKvpField.getStringValue());
        }

        // If no device data is not available, disable the entire panel
        if (wlanModeKvpField==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 {
            if (wlanManualSSID_UIC.isSelected()) {
                if (wlanSSID_UIC.getText().length() == 0)
                    errorList.add(new ValidationError("WLANSSIDValidationError"));
            }
        } catch (Exception e) {
            System.out.println("Caught Exception in NetworkWirelessView::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();
    }


}

