/**
   * 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;
  }
  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;
  }
  public void persist() {
    DataElementConcept dec = DomainObjectFactory.newDataElementConcept();
    List<DataElementConcept> decs = elements.getElements(dec);
    logger.debug("***** Inside DEC Persist ");
    int count = 0;
    sendProgressEvent(count++, decs.size(), "DECs");

    logger.debug("decs... ");
    if (decs != null) {
      for (ListIterator<DataElementConcept> it = decs.listIterator(); it.hasNext(); ) {
        DataElementConcept newDec = DomainObjectFactory.newDataElementConcept();
        dec = it.next();

        sendProgressEvent(count++, decs.size(), "DEC : " + dec.getLongName());

        List<AlternateName> passedAltNames = new ArrayList<AlternateName>();
        for (AlternateName _an : dec.getAlternateNames()) passedAltNames.add(_an);

        List<Definition> modelDefinitions = new ArrayList<Definition>();
        for (Definition _def : dec.getDefinitions()) modelDefinitions.add(_def);

        List<AdminComponentClassSchemeClassSchemeItem> passedACCSCSI = dec.getAcCsCsis();

        dec.removeDefinitions();
        dec.removeAlternateNames();

        if (!StringUtil.isEmpty(dec.getPublicId()) && dec.getVersion() != null) {
          newDec = existingMapping(dec);
          dec.setId(newDec.getId());
          for (AlternateName _an : passedAltNames) {
            persisterUtil.addAlternateName(dec, _an);
          }
          it.set(newDec);
          persisterUtil.addPackageClassification(dec);
          logger.info(PropertyAccessor.getProperty("mapped.to.existing.dec"));
          continue;
        }

        // update object class with persisted one
        if (dec.getObjectClass().getPublicId() == null)
          dec.setObjectClass(LookupUtil.lookupObjectClass(dec.getObjectClass().getPreferredName()));
        else
          dec.setObjectClass(
              LookupUtil.lookupObjectClass(
                  dec.getObjectClass().getPublicId(), dec.getObjectClass().getVersion()));

        newDec.setObjectClass(dec.getObjectClass());

        // update property with persisted one
        if (dec.getProperty().getPublicId() == null)
          dec.setProperty(LookupUtil.lookupProperty(dec.getProperty().getPreferredName()));
        else
          dec.setProperty(
              LookupUtil.lookupProperty(
                  dec.getProperty().getPublicId(), dec.getProperty().getVersion()));

        newDec.setProperty(dec.getProperty());

        logger.debug("dec name: " + dec.getLongName());
        //        logger.debug("alt Name: " + ne);

        List<String> eager = new ArrayList<String>();
        eager.add("definitions");

        // does this dec exist?
        List l = dataElementConceptDAO.find(newDec, eager);
        logger.debug("***** decs size : " + l.size());
        if (l.size() == 0) {
          logger.debug("***** one or more decs ");
          if (dec.getConceptualDomain() == null)
            dec.setConceptualDomain(defaults.getConceptualDomain());
          dec.setContext(defaults.getContext());
          dec.setLongName(
              dec.getObjectClass().getLongName() + " " + dec.getProperty().getLongName());
          dec.setPreferredDefinition(
              dec.getObjectClass().getPreferredDefinition()
                  + DEC_PREFERRED_DEF_CONCAT_CHAR
                  + dec.getProperty().getPreferredDefinition());

          dec.setPreferredName(
              ConventionUtil.publicIdVersion(dec.getObjectClass())
                  + DEC_PREFERRED_NAME_CONCAT_CHAR
                  + ConventionUtil.publicIdVersion(dec.getProperty()));

          dec.setVersion(new Float(1.0f));
          dec.setWorkflowStatus(defaults.getWorkflowStatus());

          dec.setProperty(LookupUtil.lookupProperty(dec.getProperty().getPreferredName()));

          dec.setAudit(defaults.getAudit());
          dec.setLifecycle(defaults.getLifecycle());

          StringBuilder builder = new StringBuilder();
          for (char currentChar : dec.getPreferredDefinition().toCharArray()) {
            Character replacementChar = charReplacementMap.get(currentChar);
            builder.append(replacementChar != null ? replacementChar : currentChar);
          }
          dec.setPreferredDefinition(builder.toString());
          logger.debug(
              "***** preferred name " + dec.getPreferredName() + " public ID " + dec.getPublicId());
          newDec = dataElementConceptDAO.create(dec);
          logger.info(PropertyAccessor.getProperty("created.dec"));

        } else {
          newDec = (DataElementConcept) l.get(0);
          logger.info(PropertyAccessor.getProperty("existed.dec"));

          /* if DEC alreay exists, check context
           * If context is different, add Used_by alt_name
           */
          dec.setId(newDec.getId());

          if (!newDec.getContext().getId().equals(defaults.getContext().getId())) {
            AlternateName _an = DomainObjectFactory.newAlternateName();
            _an.setName(defaults.getContext().getName());
            _an.setType(AlternateName.TYPE_USED_BY);
            persisterUtil.addAlternateName(dec, _an);
          }
        }

        dec.setId(newDec.getId());
        for (AlternateName _an : passedAltNames) {
          persisterUtil.addAlternateName(dec, _an);
        }

        for (Definition def : modelDefinitions) {
          persisterUtil.addAlternateDefinition(dec, def);
        }

        LogUtil.logAc(newDec, logger);
        logger.info("-- Public ID: " + newDec.getPublicId());
        logger.info(
            PropertyAccessor.getProperty("oc.longName", newDec.getObjectClass().getLongName()));
        logger.info(
            PropertyAccessor.getProperty("prop.longName", newDec.getProperty().getLongName()));

        dec.setAcCsCsis(passedACCSCSI);
        persisterUtil.addPackageClassification(dec);
        it.set(newDec);

        // dec still referenced in DE. Need ID to retrieve it in DEPersister.
        dec.setId(newDec.getId());
      }
    }
    logger.debug("***** End DEC persist");
  }