/**
 * CreateAndShareModule
 * @author Jae Cho
 *
 * Singleton class for interacting with Create and Share Flash game for login/register.
 *
 * Create and share requires a user to login to save the game data. When user clicks on
 * save button from the game, the following happens:
 *
 * 1. if user is logged in, user id is passed to the game.
 * 2. if user is logged out, the login dialog pops up
 *  a. if user logs in, the uid is passed to the game
 *  b. if user registers, the new uid is passed to the game
 *  c. if user does not login, cancel event is passed to the game.
 */
function CreateAndShareModule()
{
    this._name = CreateAndShareModule.NAME;

    /** uuid */
    this._uuid;

    /** action to be performd */
    this._action;

    /** the current state to pass to the game - user is logged in*/
    this._STATE_LOGIN = "login";

    /** user just registered, but haven't logged in */
    this._STATE_REGISTER = "register";

    /** user is logged out */
    this._STATE_LOGOUT = "logout";

    this.getUserId = function() {
        this._uuid = this._page.getLoggedInUserUuid();

        if (this._uuid) {
            this._action = this._STATE_LOGIN;
            this._callCreateShareAppWithUuid();
            this._status = true;
            return;
        } else {
            this.status = false;
        }

        // since this class only gets used in game page, lazily initialize to minimize overhead
        if (!this.subscriptions)
        {

            this._subscriptions = [
                AgEvent.LOGIN.subscribe(bindContext(this, "_onUserLoggedIn")),
                AgEvent.CANCEL_LOGIN.subscribe(bindContext(this, "_onCancelLogIn")),
                AgEvent.REGISTER.subscribe(bindContext(this, "_onUserRegister")),
                AgEvent.CANCEL_REGISTER.subscribe(bindContext(this, "_onCancelLogIn")),
                AgEvent.LOGOUT.subscribe(bindContext(this, "_onUserLoggedOut"))
            ];
        }

        LoginModule.showLogin();
    };

    this.getUserIdNoLoginPrompt = function() {
        this._uuid = this._page.getLoggedInUserUuid();

        if (this._uuid) {
            this._action = this._STATE_LOGIN;
            this._status = true;
            return this._uuid;
        } else {
            this.status = false;
            return -2;
        }
    };

    this._onUserLoggedIn = function()
    {
        if (this._status == LoginModule.isUserLoggedIn()) return;
        else this._status = true;

        this._uuid = g_page.getLoggedInUserUuid();
        this._action = this._STATE_LOGIN;
        //console.log("onUserLoggedIn: " + this._uuid);
        this._callCreateShareAppWithUuid();
    };

    this._onCancelLogIn = function()
    {
        this._uuid = null;
        this._action = this._STATE_LOGOUT;
        //console.log("onCancelLogIn");
        this._callCreateShareAppWithUuid();
    };

    this._onUserLoggedOut = function()
    {
        this._uuid = null;
        this._action = this._STATE_LOGOUT;
        if (this._status == LoginModule.isUserLoggedIn()) return;
        else this._status = false;
        //console.log("onCancelLogIn");
    };

    this._onUserRegister = function(uuid)
    {
        this._uuid = uuid;
        this._action = this._STATE_REGISTER;
        //console.log("onRegister - " + uuid + " " + email);
        this._callCreateShareAppWithUuid();
    };

    this._callCreateShareAppWithUuid = function() {

//        console.log("_callCreateShareAppWithUuid " + this._action + " " + this._uuid);
        var flash = getFlash("FlashContent");
        flash.setUidForCreateAndShare(this._action, this._uuid);
    };

    this._sendCreateAndShareConfirmEmail = function(gameId, creationId, playerFile) {
        var request = [{
            "methodName": "gameService.confirmCreateAndShare",
            "userUuid" : this._uuid,
            "gameId" : gameId,
            "creationId" : creationId,
            "redirectPath" : "/" + playerFile
        }];

        this._page.makeModuleAjaxCall(this, request);
    };


    /** handle AJAX response object */
    this.handleResObjects = function(resObjects)
    {
        for (var i = 0; i < resObjects.length; i++) {
            var res = resObjects[i];
            if (res["methodName"] == "gameService.confirmCreateAndShare") {
                var dialogControlCont = $("#createAndShareModInputDialog");
                var dialogControl = new DialogControl("#createAndShareModInputDialog");
                dialogControlCont.find("#casmEmail").html("An email has been sent to your address");
                dialogControlCont.find("#casmOkButton").bind("click", dialogControl, function(e) {
                    e.preventDefault();
                    e.data.hideDialog();
                });
                dialogControl.showDialog();
            }
        }
    };
}

CreateAndShareModule.prototype = new Module();

CreateAndShareModule.NAME = "CreateAndShareModule";

/** this is the function called by the create and share flash app
 * so don't change the method name w/o updating flash SDK */
function retrieveUidForCreateAndShare() {
    var module = g_page.getModule(CreateAndShareModule.NAME);
    module.getUserId();
    return "OK";
}

function retrieveUidForCreateAndShareNoLoginPrompt() {
    var module = g_page.getModule(CreateAndShareModule.NAME);
    return module.getUserIdNoLoginPrompt();
}

/** this is called from flash once create and share is saved */
function createAndShareSaveStatus(gameId, creationId, player) {

    var module = g_page.getModule(CreateAndShareModule.NAME);

    if (module._action == module._STATE_REGISTER) {
        module._sendCreateAndShareConfirmEmail(gameId, creationId, player);
    }
    
    return "OK";
}

/** this is called from flash once create and share is saved */
function getCreationId() {
    var params = StringUtil.getQueryParams(window.location.search);
    var creationId = params["creationId"];

    if (creationId) {
        return parseInt(creationId);
    }
    else return null;
}

function getFlash(flashId) {
    // For IE
    if ( ! jQuery.support.opacity ) {
        return document.getElementById(flashId);
    } else {
        return eval("document." + flashId);
    }
}