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


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

    // Data Fields currently used in this view
    KvpField baudKvpField;
    KvpField databitsKvpField;
    KvpField parityKvpField;
    KvpField stopbitsKvpField;
    KvpField flowcontrolKvpField;

    // UI Controls for each field
    JComboBox baud_UIC;
    JComboBox databits_UIC;
    JComboBox parity_UIC;
    JComboBox stopbits_UIC;
    JComboBox flowcontrol_UIC;

    /**
     * Basic constructor. Sets up the tree view and the edit panel.
     */
    public SerialBasicView() throws Exception {
        // create the KvpNode and the settings change listener
        viewSettingTree = new KvpNode();
        settingChangeListener = new DeviceChangeListener() {
            public void deviceChanged(DeviceChangeEvent e) {
                //SystemLog.debug("SerialBasicView was notified that device settings 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("SerialBasicView was notified that field "+source.toString()+" changed.");
                if (source==baud_UIC) {
                    baudKvpField.setStringValue(baud_UIC.getSelectedItem().toString());
                } else if (source==databits_UIC) {
                    databitsKvpField.setStringValue(databits_UIC.getSelectedItem().toString());
                } else if (source==parity_UIC) {
                    parityKvpField.setStringValue(parity_UIC.getSelectedItem().toString());
                } else if (source==stopbits_UIC) {
                    stopbitsKvpField.setStringValue(stopbits_UIC.getSelectedItem().toString());
                } else if (source==flowcontrol_UIC) {
                    SystemLog.debug(" flowcontrol_UIC value changed. Value is "+flowcontrol_UIC.getSelectedItem().toString());
                    flowcontrolKvpField.setStringValue(flowcontrol_UIC.getSelectedItem().toString());
                }
            }
        };

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

        String baudChoices[] = {"50", "75", "110", "134", "150", "200", "300", "600","1200", "1800", "2400", "4800", "9600", "14400", "19200", "28800", "38400", "57600", "115200", "230400"};
        baud_UIC = content.addJComboBox("Baud", "BaudDesc", baudChoices, fieldListener);
        String databitsChoices[] = {"5", "6", "7", "8"};
        databits_UIC = content.addJComboBox("Databits","DatabitsDesc",databitsChoices,fieldListener);
        String parityChoices[] = {"none", "odd", "even", "mark", "space"};
        parity_UIC = content.addJComboBox("Parity","ParityDesc",parityChoices,fieldListener);
        String stopbitsChoices[] = {"1", "2"};
        stopbits_UIC = content.addJComboBox("Stopbits","StopbitsDesc",stopbitsChoices,fieldListener);
        String flowcontrolChoices[] = {"none", "software", "hardware"};
        flowcontrol_UIC = content.addJComboBox("Flowcontrol", "FlowcontrolDesc", flowcontrolChoices, fieldListener);

        content.addVGlue();
    }

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

    /** 
     * 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 device) {
        super.setDevice(device);
        refreshViewData();
        refreshViewControls();
        device.addSettingChangeListener(settingChangeListener);
    }

    /**
     * Informs view to use the specified primary index in selecting the
     * data to display in the view. Not all views will support indexed
     * viewing and it is up to each view to define what the index is based 
     * upon. 
     * <p>
     * An example of an indexed view would be the SerialBasicView. This view
     * is indexed off the port # whose data is to be displayed in the view. An
     * external control in the SerialView lets the user select the port to view
     * and then that view instructs the SerialBasicView to use the selected 
     * port number as it's ViewIndex. Other views could use the index to base
     * their view off other integer keys such as Alarm#, Destination#,etc...
     * <p>
     * Views that do not support indexing can simply ignore this call.
     */
    public void setViewIndex(int primaryIndex) {
        super.setViewIndex(primaryIndex);
        //System.out.println("SerialBasicView.setViewIndex("+primaryIndex+")");
        // Rebind kvp fields for this port and then refresh controls
        bindFieldsForIndex(primaryIndex);
        refreshViewControls();
    }


    /** 
     * 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() {
        System.out.println("SerialBasicView.refreshViewData()");
        viewSettingTree.clear();
        int portCount=0;
        if (device!=null) {
            portCount = device.getInternalSettingTree().getChildCount("serial");
        }
        // refresh data for each port
        for (int port=1; port<=portCount; port++) {
            refreshViewDataForIndex(port);
        }
        bindFieldsForIndex(this.viewIndex);
    }

    private void refreshViewDataForIndex(int port) {
        System.out.println("SerialBasicView.refreshViewDataForIndex("+port+")");
        // Get all the serial settings for this port
        KvpNode serialSettings = viewSettingTree.mergeChild(device.getInternalSettingTree().getChild("serial", port),true);
    }


    private void bindFieldsForIndex(int port) {
        System.out.println("SerialBasicView.bindFieldsForIndex("+port+")");
        // Get all the serial settings
        KvpNode serialSettings = viewSettingTree.getChild("serial", port);

        // Point field references at data used in views
        if (serialSettings!=null) {
            baudKvpField = serialSettings.getChild("baud"); 
            databitsKvpField = serialSettings.getChild("databits"); 
            parityKvpField = serialSettings.getChild("parity"); 
            stopbitsKvpField = serialSettings.getChild("stopbits"); 
            flowcontrolKvpField = serialSettings.getChild("flowcontrol"); 
        }
    }

    /** 
     * Refreshes the state of the controls in the view to match the data in the views kvpGroup.
     */
    private void refreshViewControls() {
        System.out.println("SerialBasicView.refreshViewControls()");
        baud_UIC.setEnabled(baudKvpField!=null);
        if (baudKvpField!=null) {
            baud_UIC.setSelectedItem(baudKvpField.getStringValue());
        }
        databits_UIC.setEnabled(databitsKvpField!=null);
        if (databitsKvpField!=null) {
            databits_UIC.setSelectedItem(databitsKvpField.getStringValue());
        }
        parity_UIC.setEnabled(parityKvpField!=null);
        if (parityKvpField!=null) {
            parity_UIC.setSelectedItem(parityKvpField.getStringValue());
        }
        stopbits_UIC.setEnabled(stopbitsKvpField!=null);
        if (stopbitsKvpField!=null) {
            stopbits_UIC.setSelectedItem(stopbitsKvpField.getStringValue());
        }
        flowcontrol_UIC.setEnabled(flowcontrolKvpField!=null);
        if (flowcontrolKvpField!=null) {
            flowcontrol_UIC.setSelectedItem(flowcontrolKvpField.getStringValue());
        }
    }


    /**
     * 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) {
        // Nothing to Validate
        // errorList.add(new ValidationError("DummyValidationError"));
    }

    /**
     * This method instructs the view to place any changes the user has made within 
     * the view into the provided clusters. 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();
    }


}

