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 GetMaxAgeRange extends UDF {

    public String evaluate(Text str) {
        if (str != null) {
            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();
                }
            }
            return age;
        }
        return null;
    }

}