/* 
 *  Request.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.api.ClientI;
import com.avaya.ccs.javafxrefclient.Logger;

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

/**
 * This class is a base class for outgoing requests. This class contains methods
 * which perform logging, these can overridden in implementing classes.
 *
 * The reason for encapsulating each request is to ensure the GUI thread is not
 * blocked waiting on an SDK operation to complete.
 *
 */
public abstract class Request extends Task<Object> {

    /**
     * NO reference to the session object is held, instead it is obtained
     * through the client object.
     */
    private static ClientI client;

    private final Logger LOG;

    public Request(Logger LOG) {
        this.LOG = LOG;
        setupHandlers();
    }

    private void setupHandlers() {
        this.setFailed();
        this.setSucceeded();
        this.setCancelled();
    }

    /**
     * Any exception thrown from the call method of the implementing class will
     * be caught by the failed handler. If the failed handler is not overridden,
     * which is most cases, then the error will just be logged.
     */
    public void setFailed() {
        this.setOnFailed((WorkerStateEvent t) -> {
            String methodName = "failedHandler() ";
            Throwable f= (Throwable) t.getSource().exceptionProperty().getValue();
            LOG.error(methodName, f);
            
            Exception e = (Exception) t.getSource().exceptionProperty().getValue();
            
            LOG.error(methodName, e);
        });
    }

    public void setSucceeded() {
        this.setOnSucceeded((WorkerStateEvent t) -> {
            String methodName = "succeededHandler() ";
            LOG.trace(methodName);
        });
    }

    public void setCancelled() {
        this.setOnCancelled((WorkerStateEvent t) -> {
            String methodName = "cancelledHandler() ";
            LOG.trace(methodName);
        });
    }

    public ClientI getClient() {
        return client;
    }

    public void setClient(ClientI client) {
        Request.client = client;
    }
}
