/*
   * (non-Javadoc)
   *
   * @see org.sakaiproject.service.legacy.entity.ResourceService#merge(java.lang.String,
   *      org.w3c.dom.Element, java.lang.String, java.lang.String, java.util.Map, java.util.HashMap,
   *      java.util.Set)
   */
  public String merge(
      String siteId,
      Element root,
      String archivePath,
      String fromSiteId,
      Map attachmentNames,
      Map userIdTrans,
      Set userListAllowImport) {
    // buffer for the results log
    StringBuilder results = new StringBuilder();
    // populate SyllabusItem
    int syDataCount = 0;
    SyllabusItem syItem = null;
    if (siteId != null && siteId.trim().length() > 0) {
      try {
        NodeList allChildrenNodes = root.getChildNodes();
        int length = allChildrenNodes.getLength();
        for (int i = 0; i < length; i++) {
          Node siteNode = allChildrenNodes.item(i);
          if (siteNode.getNodeType() == Node.ELEMENT_NODE) {
            Element siteElement = (Element) siteNode;
            if (siteElement.getTagName().equals(SITE_ARCHIVE)) {
              // sakai2              NodeList pageNodes = siteElement.getChildNodes();
              //              int lengthPageNodes = pageNodes.getLength();
              //              for (int p = 0; p < lengthPageNodes; p++)
              //              {
              //                Node pageNode = pageNodes.item(p);
              //                if (pageNode.getNodeType() == Node.ELEMENT_NODE)
              //                {
              //                  Element pageElement = (Element) pageNode;
              //                  if (pageElement.getTagName().equals(PAGE_ARCHIVE))
              //                  {
              //                    NodeList syllabusNodes = pageElement.getChildNodes();
              NodeList syllabusNodes = siteElement.getChildNodes();
              int lengthSyllabusNodes = syllabusNodes.getLength();
              for (int sn = 0; sn < lengthSyllabusNodes; sn++) {
                Node syNode = syllabusNodes.item(sn);
                if (syNode.getNodeType() == Node.ELEMENT_NODE) {
                  Element syElement = (Element) syNode;
                  if (syElement.getTagName().equals(SYLLABUS)) {
                    // create a page and all syllabus tool to the page
                    // sakai2                          String page =
                    // addSyllabusToolToPage(siteId,pageElement
                    //                              .getAttribute(PAGE_NAME));
                    //                          SyllabusItem syllabusItem = syllabusManager
                    //                          .createSyllabusItem(UserDirectoryService
                    //                              .getCurrentUser().getId(), page, syElement
                    //                              .getAttribute(SYLLABUS_REDIRECT_URL));
                    String page =
                        addSyllabusToolToPage(siteId, siteElement.getAttribute(SITE_NAME));
                    // sakai2                          SyllabusItem syllabusItem = syllabusManager
                    //                          .createSyllabusItem(UserDirectoryService
                    //                              .getCurrentUser().getId(), page, syElement
                    //                              .getAttribute(SYLLABUS_REDIRECT_URL));
                    // sakai2 add--
                    SyllabusItem syllabusItem = syllabusManager.getSyllabusItemByContextId(page);
                    if (syllabusItem == null) {
                      syllabusItem =
                          syllabusManager.createSyllabusItem(
                              UserDirectoryService.getCurrentUser().getId(),
                              page,
                              syElement.getAttribute(SYLLABUS_REDIRECT_URL));
                    }
                    // added htripath: get imported redirecturl, even if syllabus item is existing.
                    else {
                      if (syElement.getAttribute(SYLLABUS_REDIRECT_URL) != null) {
                        syllabusItem.setRedirectURL(syElement.getAttribute(SYLLABUS_REDIRECT_URL));
                        syllabusManager.saveSyllabusItem(syllabusItem);
                      }
                    }
                    //
                    NodeList allSyllabiNodes = syElement.getChildNodes();
                    int lengthSyllabi = allSyllabiNodes.getLength();
                    for (int j = 0; j < lengthSyllabi; j++) {
                      Node child2 = allSyllabiNodes.item(j);
                      if (child2.getNodeType() == Node.ELEMENT_NODE) {

                        Element syDataElement = (Element) child2;
                        if (syDataElement.getTagName().equals(SYLLABUS_DATA)) {
                          List attachStringList = new ArrayList();

                          syDataCount = syDataCount + 1;
                          SyllabusData syData = new SyllabusDataImpl();
                          syData.setView(syDataElement.getAttribute(SYLLABUS_DATA_VIEW));
                          syData.setTitle(syDataElement.getAttribute(SYLLABUS_DATA_TITLE));
                          syData.setStatus(syDataElement.getAttribute(SYLLABUS_DATA_STATUS));
                          syData.setEmailNotification(
                              syDataElement.getAttribute(SYLLABUS_DATA_EMAIL_NOTIFICATION));

                          NodeList allAssetNodes = syDataElement.getChildNodes();
                          int lengthSyData = allAssetNodes.getLength();
                          for (int k = 0; k < lengthSyData; k++) {
                            Node child3 = allAssetNodes.item(k);
                            if (child3.getNodeType() == Node.ELEMENT_NODE) {
                              Element assetEle = (Element) child3;
                              if (assetEle.getTagName().equals(SYLLABUS_DATA_ASSET)) {
                                String charset = trimToNull(assetEle.getAttribute("charset"));
                                if (charset == null) charset = "UTF-8";

                                String body =
                                    trimToNull(assetEle.getAttribute("syllabus_body-html"));
                                if (body != null) {
                                  try {
                                    byte[] decoded = Base64.decodeBase64(body.getBytes("UTF-8"));
                                    body = new String(decoded, charset);
                                  } catch (Exception e) {
                                    logger.warn("Decode Syllabus: " + e);
                                  }
                                }

                                if (body == null) body = "";

                                String ret;
                                ret = trimToNull(body);

                                syData.setAsset(ret);
                                /*decode
                                NodeList assetStringNodes = assetEle
                                    .getChildNodes();
                                int lengthAssetNodes = assetStringNodes
                                    .getLength();
                                for (int l = 0; l < lengthAssetNodes; l++)
                                {
                                  Node child4 = assetStringNodes.item(l);
                                  if (child4.getNodeType() == Node.TEXT_NODE)
                                  {
                                    Text textNode = (Text) child4;
                                    syData.setAsset(textNode.getData());
                                  }
                                }*/
                              }
                              if (assetEle.getTagName().equals(SYLLABUS_ATTACHMENT)) {
                                Element attachElement = (Element) child3;
                                String oldUrl = attachElement.getAttribute("relative-url");
                                if (oldUrl.startsWith("/content/attachment/")) {
                                  String newUrl = (String) attachmentNames.get(oldUrl);
                                  if (newUrl != null) {
                                    //// if (newUrl.startsWith("/attachment/"))
                                    //// newUrl = "/content".concat(newUrl);

                                    attachElement.setAttribute(
                                        "relative-url", Validator.escapeQuestionMark(newUrl));

                                    attachStringList.add(Validator.escapeQuestionMark(newUrl));
                                  }
                                } else if (oldUrl.startsWith(
                                    "/content/group/" + fromSiteId + "/")) {
                                  String newUrl =
                                      "/content/group/"
                                          + siteId
                                          + oldUrl.substring(15 + fromSiteId.length());
                                  attachElement.setAttribute(
                                      "relative-url", Validator.escapeQuestionMark(newUrl));

                                  attachStringList.add(Validator.escapeQuestionMark(newUrl));
                                }
                              }
                            }
                          }

                          int initPosition =
                              syllabusManager.findLargestSyllabusPosition(syllabusItem).intValue()
                                  + 1;
                          syData =
                              syllabusManager.createSyllabusDataObject(
                                  syData.getTitle(),
                                  (new Integer(initPosition)),
                                  syData.getAsset(),
                                  syData.getView(),
                                  syData.getStatus(),
                                  syData.getEmailNotification());
                          Set attachSet = new TreeSet();
                          for (int m = 0; m < attachStringList.size(); m++) {
                            ContentResource cr =
                                contentHostingService.getResource((String) attachStringList.get(m));
                            ResourceProperties rp = cr.getProperties();
                            //                            			SyllabusAttachment tempAttach =
                            // syllabusManager.createSyllabusAttachmentObject(
                            //
                            //	(String)attachStringList.get(m),rp.getProperty(ResourceProperties.PROP_DISPLAY_NAME));
                            SyllabusAttachment tempAttach =
                                syllabusManager.createSyllabusAttachmentObject(
                                    cr.getId(),
                                    rp.getProperty(ResourceProperties.PROP_DISPLAY_NAME));
                            tempAttach.setName(
                                rp.getProperty(ResourceProperties.PROP_DISPLAY_NAME));
                            tempAttach.setSize(
                                rp.getProperty(ResourceProperties.PROP_CONTENT_LENGTH));
                            tempAttach.setType(
                                rp.getProperty(ResourceProperties.PROP_CONTENT_TYPE));
                            tempAttach.setUrl(cr.getUrl());
                            tempAttach.setAttachmentId(cr.getId());

                            attachSet.add(tempAttach);
                          }
                          syData.setAttachments(attachSet);

                          syllabusManager.addSyllabusToSyllabusItem(syllabusItem, syData);
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
        results.append("merging syllabus " + siteId + " (" + syDataCount + ") syllabus items.\n");

      } catch (DOMException e) {
        logger.error(e.getMessage(), e);
        results.append("merging " + getLabel() + " failed during xml parsing.\n");

      } catch (Exception e) {
        logger.error(e.getMessage(), e);
        results.append("merging " + getLabel() + " failed.\n");
      }
    }

    return results.toString();
  }
  public Map<String, String> transferCopyEntitiesRefMigrator(
      String fromContext, String toContext, List<String> ids) {
    Map<String, String> transversalMap = new HashMap<String, String>();

    try {
      logger.debug("transfer copy syllbus itmes by transferCopyEntitiesRefMigrator");
      String fromPage = fromContext;
      SyllabusItem fromSyllabusItem = syllabusManager.getSyllabusItemByContextId(fromPage);
      if (fromSyllabusItem != null) {
        Set fromSyDataSet = syllabusManager.getSyllabiForSyllabusItem(fromSyllabusItem);
        if ((fromSyDataSet != null && fromSyDataSet.size() > 0)
            || fromSyllabusItem.getRedirectURL() != null) {
          String toPage =
              addSyllabusToolToPage(toContext, SiteService.getSite(toContext).getTitle());
          SyllabusItem toSyItem = syllabusManager.getSyllabusItemByContextId(toPage);
          if (toSyItem == null) {
            toSyItem =
                syllabusManager.createSyllabusItem(
                    UserDirectoryService.getCurrentUser().getId(),
                    toPage,
                    fromSyllabusItem.getRedirectURL());
          } else if (fromSyllabusItem.getRedirectURL() != null) {
            toSyItem.setRedirectURL(fromSyllabusItem.getRedirectURL());
            syllabusManager.saveSyllabusItem(toSyItem);
          }

          Iterator fromSetIter = fromSyDataSet.iterator();
          while (fromSetIter.hasNext()) {
            SyllabusData toSyData = (SyllabusData) fromSetIter.next();
            Integer positionNo =
                new Integer(syllabusManager.findLargestSyllabusPosition(toSyItem).intValue() + 1);
            SyllabusData newToSyData =
                syllabusManager.createSyllabusDataObject(
                    toSyData.getTitle(),
                    positionNo,
                    toSyData.getAsset(),
                    toSyData.getView(),
                    toSyData.getStatus(),
                    toSyData.getEmailNotification());
            Set attachSet = syllabusManager.getSyllabusAttachmentsForSyllabusData(toSyData);
            Iterator attachIter = attachSet.iterator();
            Set newAttachSet = new TreeSet();
            while (attachIter.hasNext()) {
              SyllabusAttachment thisAttach = (SyllabusAttachment) attachIter.next();
              ContentResource oldAttachment =
                  contentHostingService.getResource(thisAttach.getAttachmentId());
              ContentResource attachment =
                  contentHostingService.addAttachmentResource(
                      oldAttachment
                          .getProperties()
                          .getProperty(ResourceProperties.PROP_DISPLAY_NAME),
                      toContext,
                      ToolManager.getTool("sakai.syllabus").getTitle(),
                      oldAttachment.getContentType(),
                      oldAttachment.getContent(),
                      oldAttachment.getProperties());
              SyllabusAttachment thisSyllabusAttach =
                  syllabusManager.createSyllabusAttachmentObject(
                      attachment.getId(),
                      attachment.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME));
              newAttachSet.add(thisSyllabusAttach);
            }
            newToSyData.setAttachments(newAttachSet);
            syllabusManager.addSyllabusToSyllabusItem(toSyItem, newToSyData);
          }
        } else {
          logger.debug(
              "importResources: no data found for syllabusItem id"
                  + fromSyllabusItem.getSurrogateKey().toString());
        }

        logger.debug("importResources: End importing syllabus data");
      }
    } catch (Exception e) {
      e.printStackTrace();
      logger.error(e.getMessage(), e);
    }

    return transversalMap;
  }