/* 
 *  EditKVPValueRequest.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.Map;

public class EditKVPValueRequest extends InteractionRequest {

    private static final Logger LOG = Logger.getLogger(EditKVPValueRequest.class);
    private String name = null;
    private String newValue = null;

    public EditKVPValueRequest(String interactionID, String name, String newValue) {
        super(LOG, interactionID);
        this.name = name;
        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.error(methodName + " no exisitng data found for interaction with ID:" + interaction.getId());
            return null;
        } else {
            // Found existing data
            Map<String, String> kvpData = existingData.getKvpData();
            if (existingData.getKvpData().containsKey(name)) {
                existingData.getKvpData().remove(name);
                kvpData.put(name, newValue);
            }

            newDataToSave = DataI.create(kvpData);
        }

        interaction.setData(newDataToSave);

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