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

import com.avaya.ccs.api.NotificationEventI;
import com.avaya.ccs.api.ResourceI;
import com.avaya.ccs.api.enums.NotificationType;

import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;

public class ResourceEventTask extends Task<ResourceData> {

    private final NotificationEventI<ResourceI> resource;
    private final ResourceDataGUI gui;
    private final InteractionDataGUI interactionGui;
    private static final Logger LOG = Logger.getLogger(ResourceEventTask.class);

    public ResourceEventTask(NotificationEventI<ResourceI> resource, ResourceDataGUI gui, InteractionDataGUI interactionGui) {
        this.resource = resource;
        this.gui = gui;
        this.interactionGui = interactionGui;
        setupJavaFXApplicationSucceededHandler();
    }

    private void setupJavaFXApplicationSucceededHandler() {
        this.setOnSucceeded((WorkerStateEvent t) -> {
            String methodName = "succeededHandler() ";
            ResourceData value = (ResourceData) t.getSource().getValue();
            t.getEventType();
            
            if (value != null) {
                if (!value.isDeleted())
                    LOG.info(methodName + "ResourceData:" + value);
                else
                    LOG.info(methodName + "Deletion of ResourceData-ID:" + value.getId());
                gui.UpdateResourceData(value);
                interactionGui.handleAddressStateEvent(value);
            } else {
                LOG.debug(methodName + " NULL");
            }
        });
    }

    /**
     * The call method executes on the incomingEvent thread
     *
     * @return
     * @throws Exception
     */
    @Override
    protected ResourceData call() throws Exception {
        String methodName = "call() ";
        ResourceData data = null;
        NotificationType type = resource.getNotificationType();
        LOG.debug(methodName + "Type:" + type + " ID:" + resource.getNotificationObject().getId());
        switch (type) {
        case UPDATE:
            data = new ResourceData(resource.getNotificationObject());
            break;
        case DELETE:
            data = new ResourceData(null);
            break;
        case ERROR:
            LOG.errorStatus(resource.getError());
            break;
        case NEW:
            data = new ResourceData(resource.getNotificationObject());
            break;
        case RESPONSE:
            break;
        case UNKNOWN:
            break;
        }
        return data;
    }
}
