/**
   * This method will check that replacing the current DE with a mapping to existing DE will not
   * conflict with any other DE.
   *
   * @param oldDe currentMapping
   * @param newDe new Mapping
   * @return null if there is no conflict. The conflicting DE if there is a conflict.
   */
  public static DataElement checkConflict(DataElement oldDe, DataElement newDe) {

    ObjectClass oc = oldDe.getDataElementConcept().getObjectClass();
    if (oc.getPublicId() != null) {
      // Verify conflicts
      if (!newDe.getDataElementConcept().getObjectClass().getPublicId().equals(oc.getPublicId())
          || !newDe.getDataElementConcept().getObjectClass().getVersion().equals(oc.getVersion())) {
        // Oc was already mapped by an existing DE. This DE conflicts with the previous mapping.
        // Now we need to find out what DE set the oc_id previously
        // return newDe;
        List<DataElement> des =
            ElementsLists.getInstance().getElements(DomainObjectFactory.newDataElement());

        for (DataElement de : des) {
          if (de.getDataElementConcept().getObjectClass()
              != oldDe.getDataElementConcept().getObjectClass()) continue;

          if (StringUtil.isEmpty(de.getPublicId()) || de.getVersion() == null) continue;

          String ocId = de.getDataElementConcept().getObjectClass().getPublicId();
          if (oldDe != de
              && ocId != null
              && !ocId.equals(newDe.getDataElementConcept().getObjectClass().getPublicId())) {
            return de;
          }
        }
        // we shouldn't be here
        return null;
      }
    }
    return null;
  }
  private void clear() {
    disableCDELinks();
    tempDE = DomainObjectFactory.newDataElement();

    ValueDomain vd = DomainObjectFactory.newValueDomain();

    List<AttributeDatatypePair> attTypesPairs =
        ElementsLists.getInstance().getElements(new AttributeDatatypePair("", ""));
    String datatype = null;
    String attributeName = LookupUtil.lookupFullName(de);
    for (AttributeDatatypePair pair : attTypesPairs) {
      if (pair.getAttributeName().equals(attributeName)) {
        datatype = pair.getDatatype();
      }
    }

    if (datatype == null) datatype = "";
    else {
      if (DatatypeMapping.getKeys().contains(datatype.toLowerCase()))
        datatype = DatatypeMapping.getMapping().get(datatype.toLowerCase());
    }

    vd.setLongName(datatype);

    tempDE.setValueDomain(vd);

    deLongNameValueLabel.setText("");
    deIdValueLabel.setText("");
    deContextNameValueLabel.setText("");
    vdLongNameValueLabel.setText("");
    conceptCodeSummaryValue.setText("");
    conceptNameSummaryValue.setText("");
  }
  private void updateFields() {
    deLongNameValueLabel.setText(tempDE.getLongName());
    deIdValueLabel.setText(ConventionUtil.publicIdVersion(tempDE));
    if (tempDE.getContext() != null) deContextNameValueLabel.setText(tempDE.getContext().getName());
    else deContextNameValueLabel.setText("");

    if (tempDE.getValueDomain() != null)
      vdLongNameValueLabel.setText(tempDE.getValueDomain().getLongName());
    else vdLongNameValueLabel.setText("");

    if (prefs.getShowConceptCodeNameSummary()) {
      List<gov.nih.nci.ncicb.cadsr.domain.Concept> concepts =
          cadsrModule.getConcepts(tempDE.getDataElementConcept().getProperty());
      if (concepts != null && concepts.size() > 0) {
        StringBuffer conceptCodeSummary = new StringBuffer();
        StringBuffer conceptNameSummary = new StringBuffer();
        for (Concept con : concepts) {
          conceptCodeSummary.append(con.getPreferredName());
          conceptCodeSummary.append(" ");
          conceptNameSummary.append(con.getLongName());
          conceptNameSummary.append(" ");
        }
        conceptCodeSummaryValue.setText(conceptCodeSummary.toString());
        conceptNameSummaryValue.setText(conceptNameSummary.toString());
      }
    }
    enableCDELinks();
  }
  public void updateNode(UMLNode node) {
    this.node = node;
    if ((node.getUserObject() instanceof DataElement)) {
      de = (DataElement) node.getUserObject();
      if (de.getPublicId() != null) {
        deLongNameValueLabel.setText("<html><body>" + de.getLongName() + "</body></html>");
        deIdValueLabel.setText(de.getPublicId() + " v" + de.getVersion());
        deContextNameValueLabel.setText(de.getContext().getName());
        vdLongNameValueLabel.setText(de.getValueDomain().getLongName());

        // if preference is set to show Concept Summary, then :
        // call cadsrModulde.getConcepts(de.getDataElementConcept().getProperty())
        // and show the 2 fields
        if (prefs.getShowConceptCodeNameSummary()) {
          List<gov.nih.nci.ncicb.cadsr.domain.Concept> concepts =
              cadsrModule.getConcepts(de.getDataElementConcept().getProperty());
          if (concepts != null && concepts.size() > 0) {
            StringBuffer conceptCodeSummary = new StringBuffer();
            StringBuffer conceptNameSummary = new StringBuffer();
            for (Concept con : concepts) {
              conceptCodeSummary.append(con.getPreferredName());
              conceptCodeSummary.append(" ");
              conceptNameSummary.append(con.getLongName());
              conceptNameSummary.append(" ");
            }
            conceptCodeSummaryValue.setText(conceptCodeSummary.toString());
            conceptNameSummaryValue.setText(conceptNameSummary.toString());
          }
        }
        enableCDELinks();
      } else clear();

      firePropertyChangeEvent(
          new PropertyChangeEvent(
              this, ButtonPanel.SWITCH, null, StringUtil.isEmpty(de.getPublicId())));
    }
  }
  public static AdminComponent checkDuplicate(DataElement currentDe, DataElement newDataElement) {
    ElementsLists elements = ElementsLists.getInstance();

    // 1. Verify that this DE will not implicitely map the OC to one
    // that is already used in the model.
    List<ObjectClass> ocs = elements.getElements(DomainObjectFactory.newObjectClass());
    if (ocs != null) {
      for (ObjectClass oc : ocs) {
        if (oc.getPublicId() != null) {
          if (currentDe.getDataElementConcept().getObjectClass() != oc)
            if (oc.getPublicId()
                .equals(newDataElement.getDataElementConcept().getObjectClass().getPublicId()))
              return oc;
        }
      }
    }

    // 2. Check that we don't already have this exact DE public ID
    List<DataElement> des = elements.getElements(DomainObjectFactory.newDataElement());
    for (DataElement de : des) {
      if (de != currentDe) {
        if (!StringUtil.isEmpty(de.getPublicId())
            && de.getPublicId().equals(newDataElement.getPublicId())) return de;
      }
    }
    //    if(des != null && ocs != null) {
    //      for(ObjectClass oc : ocs)
    ////        Map<String, DataElement> deList = new HashMap<String, DataElement>();
    //        for(DataElement de : des)
    //          if(newDataElement.getDataElementConcept().getObjectClass() ==
    // de.getDataElementConcept().getObjectClass())
    //            if(newDataElement.getPublicId() == de.getPublicId())
    //              return false;
    //    }

    return null;
  }
  private void initUI() {
    this.setLayout(new BorderLayout());

    JPanel flowPanel = new JPanel(new FlowLayout());

    JPanel mainPanel = new JPanel(new GridBagLayout());

    JPanel conceptCodeNameSummaryPanel = new JPanel(new GridBagLayout());
    JPanel topPanel = new JPanel(new BorderLayout());

    if (prefs.getShowConceptCodeNameSummary()) {
      UIUtil.insertInBag(conceptCodeNameSummaryPanel, conceptCodeSummaryLabel, 0, 1);
      UIUtil.insertInBag(conceptCodeNameSummaryPanel, conceptCodeSummaryValue, 1, 1);

      UIUtil.insertInBag(conceptCodeNameSummaryPanel, conceptNameSummaryLabel, 0, 2);
      UIUtil.insertInBag(conceptCodeNameSummaryPanel, conceptNameSummaryValue, 1, 2);
    }
    UIUtil.insertInBag(mainPanel, deLongNameTitleLabel, 0, 1);
    UIUtil.insertInBag(mainPanel, deLongNameValueLabel, 1, 1);

    UIUtil.insertInBag(mainPanel, deIdTitleLabel, 0, 2);
    UIUtil.insertInBag(mainPanel, deIdValueLabel, 1, 2);

    UIUtil.insertInBag(mainPanel, deContextNameTitleLabel, 0, 3);
    UIUtil.insertInBag(mainPanel, deContextNameValueLabel, 1, 3);

    UIUtil.insertInBag(mainPanel, vdLongNameTitleLabel, 0, 4);
    UIUtil.insertInBag(mainPanel, vdLongNameValueLabel, 1, 4);

    // Un-Comment if CDEBrowserLink can be directed to CDEBrowser application.
    //    UIUtil.insertInBag(mainPanel, cdeBrowserLinkLabel, 0, 5);
    //    UIUtil.insertInBag(mainPanel, cdeBrowserLinkValueLabel, 1, 5);

    UIUtil.insertInBag(mainPanel, clearButton, 0, 6, 2, 1);
    UIUtil.insertInBag(mainPanel, searchDeButton, 1, 6);

    cdeBrowserLinkValueLabel.addMouseListener(
        new MouseListener() {
          public void mouseClicked(MouseEvent mouseEvent) {
            String errMsg = "Error attempting to launch web browser";
            String osName = System.getProperty("os.name");
            String url = getCDEBrowserURL();
            try {
              if (osName.startsWith("Mac OS")) {
                Class fileMgr = Class.forName("com.apple.eio.FileManager");
                Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] {String.class});
                openURL.invoke(null, new Object[] {url});
              } else if (osName.startsWith("Windows"))
                Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
              else { // assume Unix or Linux
                String[] browsers = {
                  "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape"
                };
                String browser = null;
                for (int count = 0; count < browsers.length && browser == null; count++)
                  if (Runtime.getRuntime().exec(new String[] {"which", browsers[count]}).waitFor()
                      == 0) browser = browsers[count];
                if (browser == null) throw new Exception("Could not find web browser");
                else Runtime.getRuntime().exec(new String[] {browser, url});
              }
            } catch (Exception e) {
              JOptionPane.showMessageDialog(null, errMsg + ":\n" + e.getLocalizedMessage());
            }
          }

          public void mousePressed(MouseEvent e) {}

          public void mouseReleased(MouseEvent e) {}

          public void mouseEntered(MouseEvent e) {}

          public void mouseExited(MouseEvent e) {}
        });
    disableCDELinks();

    JPanel titlePanel = new JPanel();
    JLabel title = new JLabel("Map to CDE");
    titlePanel.add(title);

    flowPanel.add(mainPanel);

    topPanel.add(conceptCodeNameSummaryPanel, BorderLayout.NORTH);
    topPanel.add(titlePanel, BorderLayout.SOUTH);

    this.add(flowPanel);
    this.add(topPanel, BorderLayout.NORTH);

    searchDeButton.setActionCommand(SEARCH);
    clearButton.setActionCommand(CLEAR);

    searchDeButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            JButton button = (JButton) event.getSource();
            if (button.getActionCommand().equals(SEARCH)) {
              CadsrDialog cd = BeansAccessor.getCadsrDEDialog();

              // update dialog with current node
              cd.init(node);
              cd.setAlwaysOnTop(true);
              cd.setVisible(true);

              Object o = cd.getAdminComponent();
              if (o == null) return;

              tempDE = (DataElement) o;

              if (tempDE != null) {
                // Check for conflict
                DataElement confDe = DEMappingUtil.checkConflict(de, tempDE);
                if (confDe != null) {
                  JOptionPane.showMessageDialog(
                      null,
                      PropertyAccessor.getProperty(
                          "de.conflict",
                          new String[] {
                            de.getDataElementConcept().getProperty().getLongName(),
                            confDe.getDataElementConcept().getProperty().getLongName()
                          }),
                      "Conflict",
                      JOptionPane.ERROR_MESSAGE);
                  return;
                }
                if (tempDE != null) {
                  AdminComponent ac = DEMappingUtil.checkDuplicate(de, tempDE);
                  if (ac != null) {
                    if (ac instanceof ObjectClass)
                      JOptionPane.showMessageDialog(
                          null,
                          "This creates a duplicate mapping with "
                              + LookupUtil.lookupFullName((ObjectClass) ac),
                          "Conflict",
                          JOptionPane.ERROR_MESSAGE);
                    if (ac instanceof DataElement)
                      JOptionPane.showMessageDialog(
                          null,
                          "This creates a duplicate mapping with "
                              + ((DataElement) ac)
                                  .getDataElementConcept()
                                  .getProperty()
                                  .getLongName(),
                          "Conflict",
                          JOptionPane.ERROR_MESSAGE);
                    return;
                  }
                }
                updateFields();

                firePropertyChangeEvent(
                    new PropertyChangeEvent(this, ApplyButtonPanel.SAVE, null, true));

                //             firePropertyChangeEvent(
                //                                     new PropertyChangeEvent(this,
                // ButtonPanel.SWITCH, null, false));

                modified = true;
              }
            }
          }
        });

    clearButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            JButton button = (JButton) event.getSource();
            if (button.getActionCommand().equals(CLEAR)) {
              clear();

              firePropertyChangeEvent(
                  new PropertyChangeEvent(this, ApplyButtonPanel.SAVE, null, true));

              modified = true;
              //               fireElementChangeEvent(new ElementChangeEvent(node));

            }
          }
        });

    if ((node.getUserObject() instanceof DataElement))
      firePropertyChangeEvent(
          new PropertyChangeEvent(
              this, ButtonPanel.SWITCH, null, StringUtil.isEmpty(de.getPublicId())));
  }
  public void apply() {
    if (!modified) return;

    // uncomment to enable feature

    //     if(inheritedAttributes.isInherited(de)) {
    //       if(!userPrefs.getBoolean("de.over.vd.mapping.warning")) {
    //         DontWarnMeAgainDialog dontWarnDialog = new
    // DontWarnMeAgainDialog("de.over.vd.mapping.warning");
    //       }
    //     }

    modified = false;

    de.setLongName(tempDE.getLongName());
    de.setPublicId(tempDE.getPublicId());
    de.setVersion(tempDE.getVersion());
    de.setContext(tempDE.getContext());
    de.setValueDomain(tempDE.getValueDomain());

    fireElementChangeEvent(new ElementChangeEvent(node));

    if (tempDE.getDataElementConcept() != null) {
      if (de.getDataElementConcept().getObjectClass().getPublicId() == null
          || de.getDataElementConcept().getObjectClass().getPublicId().length() == 0) {
        JOptionPane.showMessageDialog(
            null,
            PropertyAccessor.getProperty("oc.mapping.warning"),
            "Please note",
            JOptionPane.INFORMATION_MESSAGE);
      }

      de.getDataElementConcept()
          .getObjectClass()
          .setPublicId(tempDE.getDataElementConcept().getObjectClass().getPublicId());
      de.getDataElementConcept()
          .getObjectClass()
          .setVersion(tempDE.getDataElementConcept().getObjectClass().getVersion());
      de.getDataElementConcept()
          .getObjectClass()
          .setLongName(tempDE.getDataElementConcept().getObjectClass().getLongName());

      de.getDataElementConcept()
          .getProperty()
          .setPublicId(tempDE.getDataElementConcept().getProperty().getPublicId());
      de.getDataElementConcept()
          .getProperty()
          .setVersion(tempDE.getDataElementConcept().getProperty().getVersion());

    } else {
      boolean found = false;
      List<DataElement> des =
          ElementsLists.getInstance().getElements(DomainObjectFactory.newDataElement());
      for (DataElement curDe : des) {
        if (curDe.getDataElementConcept().getObjectClass()
            == de.getDataElementConcept().getObjectClass())
          if (!StringUtil.isEmpty(curDe.getPublicId())) {
            found = true;
          }
      }
      if (!found) {
        de.getDataElementConcept().getObjectClass().setPublicId(null);
        de.getDataElementConcept().getObjectClass().setVersion(null);
      }
    }

    if (tempDE.getDataElementConcept() != null) {
      firePropertyChangeEvent(new PropertyChangeEvent(this, ButtonPanel.SWITCH, null, false));
      firePropertyChangeEvent(new PropertyChangeEvent(this, ApplyButtonPanel.REVIEW, null, true));
    } else {
      firePropertyChangeEvent(new PropertyChangeEvent(this, ButtonPanel.SWITCH, null, true));
      firePropertyChangeEvent(new PropertyChangeEvent(this, ApplyButtonPanel.REVIEW, null, false));
    }
    firePropertyChangeEvent(new PropertyChangeEvent(this, ApplyButtonPanel.SAVE, null, false));
  }