package com.bonus.canteen.core.common.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import lombok.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.function.Function;

public class RichTextUtil {
   @Generated
   private static final Logger log = LoggerFactory.getLogger(RichTextUtil.class);

   public static String getCutFileUrl(String richText) {
      return parseXml(richText, FileUrlUtil::getFileUrl);
   }

   private static String parseXml(String richText, Function<String, String> method) {
      if (StrUtil.isBlank(richText)) {
         return richText;
      } else {
         try {
            Document document = XmlUtil.parseXml(richText);
            processHtml(document.getDocumentElement(), method);
            richText = XmlUtil.toStr(document, "UTF-8", false, true);
         } catch (Exception e) {
            log.error("{}解析富文本错误:{}", new Object[]{richText, e.getMessage(), e});
         }

         return richText;
      }
   }

   private static void processHtml(Element element, Function<String, String> method) {
      NodeList children = element.getChildNodes();

      for(int i = 0; i < children.getLength(); ++i) {
         Node node = children.item(i);
         if (node instanceof Element) {
            Element child = (Element) node;
            if ("img".equalsIgnoreCase(child.getNodeName())) {
               String oldSrc = child.getAttribute("src");
               String newSrc = (String)method.apply(oldSrc);
               child.setAttribute("src", newSrc);
            }

            processHtml(child, method);
         }
      }

   }

}
