package mobvista.prd.datasource.udf;

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;

import java.util.Iterator;
import java.util.Map;

/**
 *
 * Created by fl on 2017/5/17.
 */
public class GetAgeRange extends UDF {

    public String evaluate(Text str) {
        JsonObject json = GsonUtil.String2JsonObject(str.toString());
        JsonObject ageJson = json.get("age_and_proportion").getAsJsonObject();
        Iterator<Map.Entry<String, JsonElement>> itr = ageJson.entrySet().iterator();

        String age = null;
        double max = 0.0;
        Map.Entry<String, JsonElement> entry = null;
        while (itr.hasNext()) {
            entry = itr.next();
            double temp = entry.getValue().getAsDouble();
            if (temp > max) {
                max = temp;
                age = entry.getKey();
            }
        }

        if (max < 0.5d) {
            age = "unknow";
        }

        return age;
    }

}
