package com.pinterest.secor.io.impl;

import com.pinterest.secor.common.SecorConfig;
import com.pinterest.secor.io.AdgearReader;
import com.pinterest.secor.io.KeyValue;

import net.minidev.json.JSONObject;
import net.minidev.json.JSONValue;

// Converts delivery JSON to Beh TSV
public class AdgearDeliveryJsonReader implements AdgearReader {
    private final String timestampFieldname;

    public AdgearDeliveryJsonReader(SecorConfig secorConfig) {
        timestampFieldname = secorConfig.getMessageTimestampName();
    }

    public String convert(KeyValue kv) {
        JSONObject jsonObject = null;
        Object value = JSONValue.parse(kv.getValue());
        if (value instanceof JSONObject) {
            jsonObject = (JSONObject) value;
        } else {
            return null;
        }

        Double timestamp = (Double) jsonObject.get(timestampFieldname);
        String cookieId = (String) jsonObject.get("uid");
        Integer buyerId = (Integer) jsonObject.get("buyer_id");
        Integer segmentId = (Integer) jsonObject.get("segment_id");
        Boolean segmentIsNew = (Boolean) jsonObject.get("segment_new");

        if (timestamp == null || buyerId == null || cookieId == null || segmentId == null
            || segmentIsNew == null || !segmentIsNew) {
            return null;
        }

        return String.format("%s\t%d\t%d:seg:%d\n",
                             cookieId, Math.round(timestamp), buyerId, segmentId);
    }
}

@@ -235,16 +235,98 @@
 Value;%0A%0A
+import org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;%0A%0Aimport java.util.UUID;%0A%0A
 // Conve
@@ -418,16 +418,112 @@
 eader %7B%0A
+    private static final Logger LOG = LoggerFactory.getLogger(AdgearDeliveryJsonReader.class);%0A%0A
     priv
@@ -1482,32 +1482,200 @@
 ull;%0A        %7D%0A%0A
+        try %7B%0A            UUID.fromString(cookieId);%0A        %7D catch (IllegalArgumentException e) %7B%0A            LOG.warn(%22Skipping bad UUID: %7B%7D%22, cookieId);%0A        %7D%0A%0A
         return S

Validate UUIDs.