package com.virjar.sipsoup.function.select;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.virjar.sipsoup.model.SIPNode;
import com.virjar.sipsoup.model.XpathNode;

/**
 * Created by virjar on 17/6/11.
 */
public class TagSelectFunction implements SelectFunction {
    @Override
    public List<SIPNode> call(XpathNode.ScopeEm scopeEm, Elements elements, List<String> args) {
        String tagName = args.get(0);
        List<Element> temp = Lists.newLinkedList();

        if (scopeEm == XpathNode.ScopeEm.RECURSIVE || scopeEm == XpathNode.ScopeEm.CURREC) {// 递归模式
            if ("*".equals(tagName)) {
                for (Element element : elements) {
                    temp.addAll(element.getAllElements());
                }
                // 应该是在子节点查找,本节点应该忽略
                // temp.addAll(elements);
            } else {
                temp.addAll(elements.select(tagName));
            }
        } else {// 直接子代查找
            if ("*".equals(tagName)) {
                for (Element element : elements) {
                    temp.addAll(element.children());
                }
                // temp.addAll(elements);
            } else {
                for (Element element : elements) {
                    if (StringUtils.equals(element.tagName(), tagName)) {
                        temp.add(element);
                    }
                }
            }
        }

        return Lists.transform(temp, new Function<Element, SIPNode>() {
            @Override
            public SIPNode apply(Element input) {
                return SIPNode.e(input);
            }
        });
    }

    @Override
    public String getName() {
        return "tag";
    }
}

@@ -1370,32 +1370,99 @@
 t : elements) %7B%0A
+                    for (Element child : element.children()) %7B%0A    
                 
@@ -1488,23 +1488,21 @@
 .equals(
-element
+child
 .tagName
@@ -1533,32 +1533,36 @@
                 
+    
 temp.add(element
@@ -1558,17 +1558,41 @@
 add(
-element);
+child);%0A                        %7D
 %0A   

add .