/* 
 *  RemoveKVPDataRequest.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 RemoveKVPDataRequest extends InteractionRequest {

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

    public RemoveKVPDataRequest(String interactionID, String newName) {
        super(LOG, interactionID);
        this.name = newName;
    }

    /**
     * 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 data = interaction.getData();
        if (data == null) {
            LOG.error(methodName + " no exisitng data found for interaction with ID:" + interaction.getId());
        } else {
            Map<String, String> kvpData = data.getKvpData();
            if (kvpData == null) {
                LOG.error(methodName + " no exisitng KVP data found for interaction with ID:" + interaction.getId());
            } else {
                kvpData.remove(name);

                if (kvpData.isEmpty()) {
                    LOG.trace(methodName + " last entry in kvp data has been removed, delete all data");
                    interaction.removeData();
                } else {
                    // The data object returned by getKvpData() is a copy and does not reference the 
                    // object stored within the SDK, so we need to create a new one and pass that into the setData 
                    data = DataI.create(kvpData);
                    interaction.setData(data);
                }

            }
        }

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