/*
 * ADOBE CONFIDENTIAL
 *
 * Copyright (c) 2015 Adobe Systems Incorporated. All rights reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Adobe Systems Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Adobe Systems Incorporated and its
 * suppliers and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Adobe Systems Incorporated.
 */

"use strict";

var EventEmitter  = require("events").EventEmitter;

var PreviewConfiguration = require("./PreviewServiceConfiguration"),
    PreviewGlobal = require("../../common/PreviewGlobal");

var events = new EventEmitter();

var ims = new PreviewGlobal.window.IMSInterface(),
    ref = ims.imsConnect(),
    VulcanInterface = PreviewGlobal.window.VulcanInterface,
    VulcanMessage = PreviewGlobal.window.VulcanMessage;

events.LOGGED_IN = "loggedIn";
events.NOT_LOGGED_IN = "notLoggedIn";
events.LOGGING_IN = "loggingIn";
events.ERROR = "error";

var aamSignoutNotification = VulcanMessage.TYPE_PREFIX + "com.adobe.aam.AAMSIGNOUTStatus";

VulcanInterface.addMessageListener(aamSignoutNotification, function () {
    events.emit(events.NOT_LOGGED_IN);
});

function handleImsFetchTokenEvent(event) {
    var extensionId = event.extensionId,
        tokenInfo = event.data;

    if (extensionId === PreviewGlobal.csInterface.getExtensionID()) {
        if (tokenInfo && tokenInfo.token_type === "bearer") {
            exports.accessToken = tokenInfo.access_token;
            events.emit(events.LOGGED_IN);
        } else {
            events.emit(events.ERROR);
        }

        ims.removeEventListener(ims.events.imsFetchAccessToken, handleImsFetchTokenEvent);
    }
}

function init() {
    ims.addEventListener(ims.events.imsFetchAccessToken, handleImsFetchTokenEvent);

    ims.imsGetCurrentUserIdHelper(function (userId) {
        if (!userId) {
            events.emit(events.NOT_LOGGED_IN);
            return;
        } else {
            events.emit(events.LOGGING_IN);
        }

        exports.accountGuid = userId;
        if (!ims.imsFetchAccessToken(ref, PreviewConfiguration.clientId, PreviewConfiguration.clientSecret, userId, 0, "openid,AdobeID")) {
            events.emit(events.ERROR);
        }
    });
}

function shutdown() {
    ims.imsDisconnect(ref);
}


exports.init = init;
exports.shutdown = shutdown;
exports.events = events;
exports.enabled = PreviewConfiguration.enabled;
