package com.virjar.vscrawler.core.processor;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Function;
import com.google.common.collect.Lists;

import java.util.Collection;
import java.util.List;

/**
 * Created by virjar on 2018/1/20.
 * <br>
 * 还是使用object存储抓取结果,避免一些不必要的转换
 *
 * @author virjar
 * @since 0.2.6
 */
public class GrabResult extends CrawlResult {
    private List<Object> entityResult = Lists.newLinkedList();

    @Override
    public void addResult(String result) {
        entityResult.add(result);
    }

    public void addResult(Object entity) {
        entityResult.add(entity);
    }

    @Override
    public void addResults(Collection<?> resultsIn) {
        entityResult.addAll(resultsIn);
    }

    @Override
    public List<String> allResult() {
        return Lists.transform(entityResult, new Function<Object, String>() {
            @Override
            public String apply(Object input) {
                if (input instanceof CharSequence) {
                    return input.toString();
                }
                return JSONObject.toJSONString(input);
            }
        });
    }

    public List<Object> allEntityResult() {
        return Lists.newArrayList(entityResult);
    }
}

@@ -159,16 +159,83 @@
 .Lists;%0A
+import com.google.common.collect.Maps;%0A%0Aimport java.util.ArrayList;
 %0Aimport 
@@ -278,16 +278,38 @@
 il.List;
+%0Aimport java.util.Map;
 %0A%0A/**%0A *
@@ -529,16 +529,172 @@
 dList();
+%0A    private Map%3CString, Object%3E fieldMap = Maps.newHashMap();%0A%0A    public void putField(String key, Object value) %7B%0A        fieldMap.put(key, value);%0A    %7D
 %0A%0A    @O
@@ -1040,30 +1040,47 @@
 ) %7B%0A        
-return
+List%3CString%3E entities =
  Lists.trans
@@ -1406,101 +1406,542 @@
     
-%7D%0A%0A    public List%3CObject%3E allEntityResult() %7B%0A        return Lists.newArrayList(entityResult
+    if (fieldMap.size() == 0) %7B%0A            return entities;%0A        %7D%0A        ArrayList%3CString%3E ret = Lists.newArrayListWithExpectedSize(entities.size() + 1);%0A        ret.addAll(entities);%0A        ret.add(JSONObject.toJSONString(fieldMap));%0A        return ret;%0A    %7D%0A%0A    public List%3CObject%3E allEntityResult() %7B%0A        return Lists.newArrayList(entityResult);%0A    %7D%0A%0A    public Object getFiled(String key) %7B%0A        return fieldMap.get(key);%0A    %7D%0A%0A    public Map%3CString, Object%3E allFiled() %7B%0A        return Maps.newHashMap(fieldMap
 );%0A 

put field for grab result