var chalk = require('chalk');
var log = require('fancy-log');
var args = require('minimist')(process.argv.slice(2));
var AvayaCustomerServices = require("./libs/AvayaCustomerServices.node.js");

// App name
const CLIENT_ID = 'testApp';

// Server endpoints
const API_URL = 'https://BREEZE-FQDN/services/UnifiedAgentController/UACAPI';
const BROADCAST_URL = 'https://BREEZE-FQDN/services/Broadcast-UnifiedAgentController/broadcast';

var token = { header: 'Authorization', value: args.token };
var tokenData = parseSSOToken(token.value);

// UAC Configuration for Avaya Customer Services SDK
var config = {
    uacConfiguration: new AvayaCustomerServices.Config.UACConfiguration({
        enabled: true,
        clientInfo: { id: CLIENT_ID },
        serverInfo: { apiUrl: API_URL },
        notificationInfo: { broadcastUrl: BROADCAST_URL, fallbackTransport: 'websocket' },
        authenticationInfo: { enabled: true, tokens: ['Authorization'] }
    })
};

var notificationConfig = config.uacConfiguration.notificationInfo;
notificationConfig.onClose(function () {
    console.log(chalk.red('notificationConfig.addOnCloseCallback'));
    process.exit();
});

// Initialize the Avaya Customer Services SDK
var client = new AvayaCustomerServices(config);
// Custom logger for internal SDK events
log.debug = log.log = log;
client.registerLogger(log);

var clientSession = client.createClientSession();

// Set token to SDk token store and start session
clientSession.setToken(token);

// Display resource if acquired
clientSession.addOnResourceAcquiredCallback(function () {
    console.log(chalk.green('clientSession.addOnResourceAcquiredCallback'));
});

// Hide resource if released
clientSession.addOnResourceReleasedCallback(function () {
    console.log(chalk.green('clientSession.addOnResourceReleasedCallback'));
});

clientSession.addOnErrorCallback(function () {
    console.log(chalk.red('clientSession.addOnErrorCallback'));
});

clientSession.addOnCloseCallback(function () {
    console.log(chalk.blue('clientSession.addOnCloseCallback'));
});

clientSession.addOnClientSessionRestartedCallback(function () {
    console.log(chalk.red('clientSession.addOnClientSessionRestartedCallback'));
});

clientSession.addOnClientSessionClosedCallback(function () {
    console.log(chalk.red('clientSession.addOnClientSessionClosedCallback'));
});

clientSession.addOnClientSessionStartedCallback(function () {
    console.log(chalk.green('clientSession.addOnClientSessionStartedCallback'));
});

clientSession.getConfiguration(tokenData.authHandle).then(function (data) {

    // And start the client session (initiates atmosphere)
    clientSession.start();

    // Initialise Agent module
    var agent = clientSession.createAgent();

    // Attach listener for agent activate event
    agent.addOnActivatedCallback(function () {
        console.log(chalk.green('agent.addOnActivatedCallback'));
    });

    // Attach listener for agent activate event
    agent.addOnDeactivatedCallback(function () {
        console.log(chalk.red('agent.addOnDeactivatedCallback'));
    });


    // Attach listener for agent login pending event
    agent.addOnStateLoginPendingCallback(function () {
        console.log(chalk.green('agent.addOnStateLoginPendingCallback'));
    });

    // Attach listener for agent ready event
    agent.addOnStateReadyCallback(function () {
        console.log(chalk.green('agent.addOnStateReadyCallback'));
    });

    // Attach listener for agent not ready pending event
    agent.addOnStateNotReadyPendingCallback(function () {
        console.log(chalk.green('agent.addOnStateNotReadyPendingCallback'));
    });

    // Attach listener for agent not ready event
    agent.addOnStateNotReadyCallback(function () {
        console.log(chalk.green('agent.addOnStateNotReadyCallback'));
    });

    // Attach listener for agent logout pending event
    agent.addOnStateLogoutPendingCallback(function () {
        console.log(chalk.green('agent.addOnStateLogoutPendingCallback'));
    });

    // Attach listener for agent logged out event
    agent.addOnStateLoggedOutCallback(function () {
        console.log(chalk.green('agent.addOnStateLoggedOutCallback'));
    });

    // Attach listener for agent unknown state event
    agent.addOnStateUnknownCallback(function () {
        console.log(chalk.green('agent.addOnStateUnknownCallback'));
    });

    // Initialise Work module
    var work = clientSession.createWork();

    // Attach listener to new interaction event
    work.addOnInteractionCreatedCallback(function (message) {

        console.log(chalk.green('work.addOnInteractionCreatedCallback'));

        // Search interaction collection to find interaction by id
        var collection = work.getInteractions();
        var interaction = collection.find({ id: message.id });

        interaction.addOnInteractionActiveCallback(function () {
            console.log(chalk.green('interaction.addOnInteractionActiveCallback'));
        });

        interaction.addOnInteractionHeldCallback(function () {
            console.log(chalk.green('interaction.addOnInteractionHeldCallback'));
        });

        interaction.addOnInteractionUnheldCallback(function () {
            console.log(chalk.green('interaction.addOnInteractionUnheldCallback'));
        });

        interaction.addOnInteractionMediaAddedCallback(function () {

            console.log(chalk.green('interaction.addOnInteractionMediaAddedCallback'));

            var interactionMedia = interaction.getInteractionMedia();

            interactionMedia.addMessageReceivedCallback(function () {
                console.log(chalk.green('interactionMedia.addMessageReceivedCallback'));
            });

            interactionMedia.addOnIsTypingCallback(function () {
                console.log(chalk.green('interactionMedia.addOnIsTypingCallback'));
            });
        });
    });

    // Detach listeners and remove element
    work.addOnInteractionDeletedCallback(function () {
        console.log(chalk.green('work.addOnInteractionDeletedCallback'));
    });

    setTimeout(function () {
        agent.activate(data.user.userHandle);
    }, 10000);


});

setTimeout(function () {
    client.removeClientSession();
}, 20000);

/**
 * Parse JSON Web Token
 *
 * @private
 * @returns {Object}
 */
function parseSSOToken(token) {
    var parsedJWT;
    var encodedJWT = token.split(' ')[1];
    if (!encodedJWT) return;

    var payload = encodedJWT.split('.')[1];
    if (!payload) return;

    try {
        var atob = new Buffer(payload, 'base64').toString('binary');
        parsedJWT = JSON.parse(atob);
    } catch (error) {
        parsedJWT = {};
    }
    return {
        authHandle: parsedJWT.sub,
        expires: parsedJWT.exp,
        jwt: encodedJWT
    };
}
