/* 
 *  UserEventTask.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.UserI;
import com.avaya.ccs.api.enums.NotificationType;
import com.avaya.ccs.javafxrefclient.request.GetUserDataRequest;

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

public class UserEventTask extends Task<UserData> {

    private final NotificationEventI<UserI> user;
    private final UserDataGUI gui;
    private final SupervisorDataGUI superGui;
    private static final Logger LOG = Logger.getLogger(UserEventTask.class);

    public UserEventTask(NotificationEventI<UserI> user, UserDataGUI gui, SupervisorDataGUI gui2) {
        this.user = user;
        this.gui = gui;
        this.superGui = gui2;
        setupJavaFXApplicationSucceededHandler();
    }

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

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