package sample.application;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sample.config.UserConfig;
import sample.core.Authentication;
import sample.core.CallControl;
import sample.core.ClientSession;
import sample.core.exception.OTRestClientException;

/**
 * <pre>
 * Code sample to make a simple call
 * 
 *   First of all it gets users sample.config, and then authenticates them.
 *   After it opens a session for the caller.
 *   And then only the make call is initiated; user 1 calls user 2.
 *   The callee is ringing but doesn't answer.
 *   After 7s the call is released by the caller, the callee doesn't ring anymore.
 *   At last the caller's session is closed.
 *
 *   Note:
 *   To be able to make this scenario work, caller's device has to correctly support the 3PCC, and also it has to be in auto-answer mode.
 *   Auto-answer mode can be replaced by answering manually when the caller is ringing.
 * </pre>
 */
public class Sample1MakeCall {

    private static final Logger LOGGER = LoggerFactory.getLogger(Sample1MakeCall.class);

    public static void main(String[] args) throws OTRestClientException {

        ClientSession user1Session = null;

        try {
            // Read the configuration of the users involved in the sample
            UserConfig user1Config = UserConfig.create("alice");
            UserConfig user2Config = UserConfig.create("bob");

            // User 1 authentication
            Authentication user1Authentication = new Authentication();
            user1Authentication.authenticate(user1Config);

            // Open session
            user1Session = new ClientSession(user1Config.getLogin(), user1Authentication);
            user1Session.open(); // a session is needed for the user to be able to make the "make-call"

            //
            // MAKE CALL : User 1 calls User 2
            // Note that the caller's device has to handle the 3PCC.
            // The device also must be in auto answer mode, otherwise it will ring (in that case it can be answered manually).
            //
            LOGGER.debug("Make call {} -> {}", user1Config.getLogin(), user2Config.getLogin());
            CallControl callControl = new CallControl(user1Config, user1Authentication.getCookie(), user1Session);
            callControl.makeCallRequest(user2Config);

            // User 2 is ringing, wait...
            waitInSeconds(7);

            // User 1 (the caller) releases the call
            LOGGER.debug("Release call");
            callControl.releaseAllCallsRequest();

        } finally {
            // Close the session
            if (user1Session != null) {
                user1Session.close();
            }
        }
    }

    private static void waitInSeconds(int seconds) {
        try {
            Thread.sleep(TimeUnit.MILLISECONDS.convert(seconds, TimeUnit.SECONDS));
        } catch (InterruptedException ignore) {
        }
    }
}
