/* 
 *  GetResourceDataRequest.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 java.util.ArrayList;
import java.util.List;

import com.avaya.ccs.api.ResourceI;
import com.avaya.ccs.javafxrefclient.Logger;
import com.avaya.ccs.javafxrefclient.ResourceData;
import com.avaya.ccs.javafxrefclient.ResourceDataGUI;

import javafx.concurrent.WorkerStateEvent;

public class GetResourceDataRequest extends SessionRequest {

    private static final Logger LOG = Logger.getLogger(GetResourceDataRequest.class);
    private final ResourceDataGUI gui;

    public GetResourceDataRequest(ResourceDataGUI gui) {
        super(LOG);
        this.gui = gui;
    }

    /**
     * The call method executes on the outgoingRequest thread
     *
     * @return
     * @throws Exception
     */
    @Override
    protected Object call() throws Exception {
        String methodName = "call() ";
        LOG.trace(methodName + "+");
        List<ResourceData> data = new ArrayList<>();
        List<ResourceI> resources = new ArrayList<>();
        resources.addAll(getSession().getResources());
        for (ResourceI i : resources) {
            data.add(new ResourceData(i));
        }
        LOG.trace(methodName + "+");
        return data;
    }

    @Override
    public void setSucceeded() {
        this.setOnSucceeded((WorkerStateEvent t) -> {
            String methodName = "succeededHandler() ";
            // The value is returned from the call() method above so
            // will always be the correct type
            // The only way to check the type to avoid a warning is to
            // iterate over the list, instead suppress the warning
            @SuppressWarnings("unchecked")
            List<ResourceData> value = (List<ResourceData>) t.getSource().valueProperty().getValue();
            if (value != null) {
                LOG.debug(methodName + "List<ResourceData>:" + value);
                gui.UpdateResourceData(value);
            } else {
                LOG.debug(methodName + " NULL");
            }
        });
    }
}
