/* 
 *  SessionEventTask.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.SessionI;
import com.avaya.ccs.api.enums.NotificationType;

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

public class SessionEventTask extends Task<SessionData> {

    private final NotificationEventI<SessionI> session;
    private final JavaFXRefClient gui;
    private final ClientSessionExecutor ccs;
    private static final Logger LOG = Logger.getLogger(SessionEventTask.class);

    public SessionEventTask(NotificationEventI<SessionI> session, ClientSessionExecutor ccs, JavaFXRefClient gui) {
        this.session = session;
        this.gui = gui;
        this.ccs = ccs;
        setupJavaFXApplicationSucceededHandler();

    }

    private void setupJavaFXApplicationSucceededHandler() {
        this.setOnSucceeded((WorkerStateEvent t) -> {
            String methodName = "succeededHandler() ";
            SessionData value = (SessionData) t.getSource().getValue();
            if (value != null) {
                LOG.info(methodName + "SessionData:" + value);
                gui.updateSessionData(value);
            } else {
                LOG.debug(methodName + " NULL");
            }
        });
    }

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