/* 
 *  SignInRequest.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.javafxrefclient.ClientSessionExecutor;
import com.avaya.ccs.javafxrefclient.ConnectionDetails;
import com.avaya.ccs.javafxrefclient.Logger;
import com.avaya.ccs.api.ClientI;
import com.avaya.ccs.api.enums.Profile;
import com.avaya.ccs.api.exceptions.InvalidArgumentException;

public class SignInRequest extends Request {

    private static final Logger LOG = Logger.getLogger(SignInRequest.class);
    private final ClientSessionExecutor clientSessionExe;
    private final ConnectionDetails connectionDetails;

    public SignInRequest(ClientSessionExecutor clientSessionExe, ConnectionDetails connectionDetails) {
        super(LOG);
        this.clientSessionExe = clientSessionExe;
        this.connectionDetails = connectionDetails;
    }

    /**
     * The call method executes on the outgoingRequest thread
     *
     * @return
     * @throws Exception
     */
    @Override
    protected Object call() throws Exception {
        String methodName = "call() ";
        
        if (getClient() == null) {            
            ClientI client = ClientI.create(connectionDetails.getServer(), Profile.AgentDesktop, "JavaFxCcsReferenceClient", null);
            clientSessionExe.setClient(client);
            setClient(client);
        }
        getClient().setAutoReconnect(connectionDetails.isAutoReconnect());
        getClient().setServer(connectionDetails.getServer());
        
        if (getClient().getSession() == null) {
            LOG.trace(methodName + "session == null");
            try {
                getClient().signin(connectionDetails.getUsername(), connectionDetails.getPassword(), clientSessionExe, clientSessionExe);
            } catch (InvalidArgumentException ex) {
                return ex;
            }
            LOG.trace(methodName + "signin -");
            return null;
        } else {
            LOG.trace(methodName + "session != null, signin ignored");
        }
        return null;
    }
}
