package com.priusis.client.util.converter;

import com.fasterxml.jackson.databind.JsonNode;
import com.priusis.client.data.kv.KvEntry;
import com.priusis.client.service.data.DeviceData;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import static com.priusis.client.util.JsonTools.fromString;
import static com.priusis.client.util.JsonTools.getKvEntries;

/**
 * Created by priusis on 15.05.17.
 */
@Data
@Slf4j
public class BasicJsonConverter{

    protected String filterExpression;
    protected String deviceNameJsonExpression;
    protected String deviceTypeJsonExpression;
    private ConcurrentHashMap<String, SimpleDateFormat> formatters = new ConcurrentHashMap<>();

    public DeviceData parseBody(String body) {
        try {
            JsonNode payload = fromString(body);
            return parseDeviceData(payload);
        } catch (Exception e) {
            log.error("Exception occurred while parsing json request body [{}]", body, e);
            throw new RuntimeException(e);
        }
    }

    protected DeviceData parseDeviceData(JsonNode payload) throws ParseException {
        //long ts = System.currentTimeMillis();
        List<KvEntry> attrData = getKvEntries(payload);
        return new DeviceData(attrData);
    }

}
