/* 
 *  AddKVPToExistingDataRequest.java
 * 
 *  Copyright 2016 Avaya Inc. All Rights Reserved.
 * 
 *  Usage of this source is bound to the terms described
 *  in AvayaLicenseSDK.rtf.
 * 
 *  Avaya - Confidential & Proprietary. Use pursuant to your signed agreement
 *  or Avaya Policy
 * 
 */
package com.avaya.ccs.javafxrefclient.request;

import com.avaya.ccs.javafxrefclient.Logger;
import com.avaya.ccs.api.DataI;
import com.avaya.ccs.api.InteractionI;
import java.util.HashMap;
import java.util.Map;

public class AddKVPToExistingDataRequest extends InteractionRequest {

    private static final Logger LOG = Logger.getLogger(AddKVPToExistingDataRequest.class);
    private String newName = null;
    private String newValue = null;

    public AddKVPToExistingDataRequest(String interactionID, String newName, String newValue) {
        super(LOG, interactionID);
        this.newName = newName;
        this.newValue = newValue;
    }

    /**
     * The call method executes on the outgoingRequest thread
     *
     * @return
     * @throws Exception
     */
    @Override
    protected Object call() throws Exception {
        String methodName = "call() ";
        LOG.trace(methodName + "+");
        InteractionI interaction = getInteraction();
        DataI existingData = interaction.getData();
        DataI newDataToSave;
        if (existingData == null) {
            LOG.trace(methodName + " no exisitng data found for interaction with ID:" + interaction.getId());
            //Need to create a new data object
            HashMap<String, String> map = new HashMap<>();
            map.put(newName, newValue);
            newDataToSave = DataI.create(map);
        } else {
            // Found existing data, so combing with new data
            Map<String, String> kvpData = new HashMap<>();
            kvpData.putAll(existingData.getKvpData());
            kvpData.put(newName, newValue);
            newDataToSave = DataI.create(kvpData);
        }

        interaction.setData(newDataToSave);
        LOG.trace(methodName + "-");
        return null;
    }
}
