package mobvista.prd.datasource.udf;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import mobvista.prd.datasource.util.GsonUtil;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;

/**
 * Created by fl on 2017/5/17.
 */
public class GetInterestInfo extends UDF {
    private StringBuilder builder = new StringBuilder();
    private static final String dataSplit = "\t";

    public String evaluate(Text str) {
        JsonArray array = GsonUtil.String2JsonArray(str.toString());
        for (JsonElement element : array) {
            JsonObject obj = element.getAsJsonObject();
            JsonArray tagArray = obj.get("tag").getAsJsonArray();
            for (JsonElement tagElement : tagArray) {
                JsonObject tagObj = tagElement.getAsJsonObject();
                String firstLevel = tagObj.get("1") != null ? tagObj.get("1").getAsString() : "";
                String sencondLevel = tagObj.get("2") != null ? tagObj.get("2").getAsString() : "";

                builder.setLength(0);
                builder.append(firstLevel).append(dataSplit).append(sencondLevel);
            }
        }
        return builder.toString();
    }
}
