/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2005/08/17, 11:31
!  AUTHOR(S): KOGA, Junichiro
!  File : ComboBoxPhase.java
!  
!  Contact address :  Phase System Consortium
!                     E-mail: phase_system@nims.go.jp URL https://azuma.nims.go.jp
!
!
!   Since 2002, this program set had been intensively developed as a part of the following 
!  national projects supported by the Ministry of Education, Culture, Sports, Science and
!  Technology (MEXT) of Japan; "Frontier Simulation Software for Industrial Science
!  (FSIS)" from 2002 to 2005, "Revolutionary Simulation Software (RSS21)" from 2006 to
!  2008. "Research and Development of Innovative Simulation Software (RISS)" from 2008
!  to 2013. These projects is lead by the Center for Research on Innovative Simulation 
!  Software (CISS), the Institute of Industrial Science (IIS), the University of Tokyo.
!   Since 2013, this program set has been further developed centering on PHASE System
!  Consortium. 
!   The activity of development of this program set has been supervised by Takahisa Ohno.
!
!=======================================================================
 */
package ciss.phase_viewer.primitiveguis;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.util.EventObject;
import java.util.Vector;

import javax.swing.JComponent;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;

import org.apache.log4j.Logger;

import ciss.phase_viewer.common.Command;
import ciss.phase_viewer.common.ConstParameters;
import ciss.phase_viewer.inputinterface.InputInterface;
import ciss.phase_viewer.inputinterface.InputInterfaceEntry;
import ciss.phase_viewer.inputinterface.InputInterfaceEntryChangeEvent;
import ciss.phase_viewer.inputinterface.InputInterfaceEntryChangeListener;
import ciss.phase_viewer.inputinterface.InputInterfacePrimitiveEntry;

/**
 * 
 * @author KOGA, Junichiro
 */
public class ComboBoxPhase extends ToolTippedCombo implements Command,
        InputInterfaceEntryChangeListener {
    private static Logger logger = Logger.getLogger(ComboBoxPhase.class
            .getName());

    private String[] inputSpecifications;

    private InputInterface inputinterface;

    private String[] choices;

    private Vector disabableGUIs = new Vector();

    private boolean isUnit = false;

    public ComboBoxPhase(String[] choices, String[] inputSpecifications,
            InputInterface inputinterface) {
        super(choices);
        this.choices = choices;
        this.inputSpecifications = inputSpecifications;
        this.inputinterface = inputinterface;
        inputinterface.addInputInterfaceEntryChangeListener(this);
    }

    public ComboBoxPhase(String[] choices, String[] inputSpecifications,
            InputInterface inputinterface, boolean isUnit) {
        super(choices);
        this.choices = choices;
        this.inputSpecifications = inputSpecifications;
        this.inputinterface = inputinterface;
        this.isUnit = isUnit;
        inputinterface.addInputInterfaceEntryChangeListener(this);
    }

    public void silentUpdate() {
        String newText = (String) super.getSelectedItem();
        InputInterfacePrimitiveEntry entry = inputinterface
                .getInputInterfacePrimitiveEntry(inputSpecifications[0]);
        String[] fn = inputSpecifications[0].split("\\.");
        String name = fn[fn.length - 1];
        if (!isUnit) {
            entry.setUnit("");
            entry.setValue(newText.trim());
        } else {
            entry.setUnit(newText.trim());
        }
        if (!(newText == null)
                && !newText.trim().equalsIgnoreCase(
                        ConstParameters.NO_SELECTION)) {
            inputinterface.replaceEntry(entry, this, false);
            logger.debug("replaced: " + entry.getName() + "="
                    + entry.getValue());
        } else {
            inputinterface.removeEntry(entry, this, false);
            logger.debug("removed: " + entry.getName() + "=" + entry.getValue());
        }
    }

    public void execute(EventObject e) {
        if (e instanceof ItemEvent) {
            logger.debug("item event...");
        } else if (e instanceof ActionEvent) {
            logger.debug("actionevent...");
        } else if (e instanceof PopupMenuEvent) {
            logger.debug("pop-up menu event...");
        }

        String newText = (String) super.getSelectedItem();
        logger.debug("inputSpec: " + inputSpecifications[0]);
        InputInterfacePrimitiveEntry entry = inputinterface
                .getInputInterfacePrimitiveEntry(inputSpecifications[0]);

        String[] fn = inputSpecifications[0].split("\\.");
        String name = fn[fn.length - 1];

        entry.saveState();

        entry.setName(name);
        if (!isUnit) {
            entry.setUnit("");
            entry.setValue(newText.trim());
        } else {
            entry.setUnit(newText.trim());
        }

        if (!(newText == null)
                && !newText.trim().equalsIgnoreCase(
                        ConstParameters.NO_SELECTION)) {
            inputinterface.replaceEntry(entry, this);
            logger.debug("replaced: " + entry.getName() + "="
                    + entry.getValue());
            logger.debug("at : "
                    + inputinterface.getCurrentBlock().getFullName());
        } else {
            inputinterface.removeEntry(entry, this);
            logger.debug("removed: " + entry.getName() + "=" + entry.getValue());
            logger.debug("from block: "
                    + inputinterface.getCurrentBlock().getFullName());
        }
        disableRegisteredGUI();
    }

    /**
     * 「登録されたGUIをdiableにする」操作を直接行う
     */
    public void disableRegisteredGUI() {
        for (int i = 0; i < disabableGUIs.size(); i++) {
            Vector disset = (Vector) disabableGUIs.get(i);
            int[] index = (int[]) disset.get(0);
            JComponent jcomponent = (JComponent) disset.get(1);
            int selectedIndex = super.getSelectedIndex();
            boolean enable = true;
            for (int j = 0; j < index.length; j++) {
                // logger.debug("diabable gui, index: "+index[j]);
                if (selectedIndex == index[j]) {
                    enable = false;
                    continue;
                }
            }
            jcomponent.setEnabled(enable);
        }
    }

    public void inputInterfaceInitializing() {
        removeListeners();
        setSelectedIndex(0);
        restoreListeners();
    }

    public void inputInterfaceInitialized() {

    }

    private ActionListener[] alists;

    private PopupMenuListener[] plists;

    public void removeListeners() {
        alists = getActionListeners();
        plists = getPopupMenuListeners();
        if (alists != null) {
            for (int i = 0; i < alists.length; i++) {
                removeActionListener(alists[i]);
            }
        }
        if (plists != null) {
            for (int i = 0; i < plists.length; i++) {
                removePopupMenuListener(plists[i]);
            }
        }
    }

    public void restoreListeners() {
        if (alists != null) {
            for (int i = 0; i < alists.length; i++) {
                addActionListener(alists[i]);
            }
        }
        if (plists != null) {
            for (int i = 0; i < plists.length; i++) {
                addPopupMenuListener(plists[i]);
            }
        }
    }

    public void inputInterfaceEntryChanged(InputInterfaceEntryChangeEvent evt) {
        if (evt.getSource() == this) {
            return;
        }

        logger.debug("at inputInterfaceEntryChanged");

        String tag = evt.getTag();
        InputInterfaceEntry entry = evt.getEntry();
        if (entry.getEntryType() != InputInterfaceEntry.PRIMITIVE) {
            return;
        }

        InputInterfacePrimitiveEntry pentry = (InputInterfacePrimitiveEntry) entry;
        String fullName = tag + "." + pentry.getName();

        String rep = "";
        if (isUnit) {
            rep = pentry.getUnit();
        } else {
            rep = pentry.getValue();
        }

        if (rep == null || rep.trim().length() == 0) {
            return;
        }

        removeListeners();

        for (int ii = 0; ii < inputSpecifications.length; ii++) {
            if (fullName.trim()
                    .equalsIgnoreCase(inputSpecifications[ii].trim())) {
                logger.debug("replace string: " + rep + " (fullName: "
                        + fullName + ")");
                int irep = -1;
                for (int i = 0; i < getItemCount(); i++) {
                    if (((String) getItemAt(i)).equalsIgnoreCase(rep)) {
                        irep = i;
                        break;
                    }
                }
                if (irep == -1) {
                    setSelectedIndex(0);
                    return;
                }
                setSelectedIndex(irep);
            }
        }

        restoreListeners();
    }

    public void setDisabableGUI(int[] index, JComponent jcomponent) {
        Vector disset = new Vector();
        disset.addElement(index);
        disset.addElement(jcomponent);
        disabableGUIs.addElement(disset);
    }

}
