// this file contains main Myspace Connect logic

// Workflow
// *** read http://wiki.developers.myspace.com/index.php/Connect/Authentication_and_Authorization
// ------------------------------------------------------------
// 1. Temporary user, on login dialog:
//   a) show "connect with myspace" button
//      when user clicks it, it performs scenario 1,2 or 3 from ***
//      after authorized user comes back from myspace:
//      test if user is already associated with some of our accounts:
//      * if yes, perform auto-login
//      * if not, present special registration form
//        - do not provide password fields
//        - pre-fill form fields with data from Myspace
//        -> when user creates account this way, make it associated with Myspace user
//        -> if user enters exising email, present special UI for password and let him log in and associate automatically (Peter)
//      in both cases transfer all temporary data to real account (if any)
// 
// 2. Logged user, on "My Account" page:
//    a) if account is already connected with myspace => show "reconnect" and "disconnect" actions
//    b) if account is not connected => show "connect with myspace" button
//       when user clicks it, it performs scenario 1,2 or 3 from ***
//       after authorized user comes back from myspace:
//       * assign this myspace user to this account
//    
//    reconnect action works similar to b) but first forces logout from myspace (it is just safer to ask user again for his myspace credentials, than explaining it in the text)
//    disconnect action simply removes myspace user association from our account
//
// TODO: account.php has no support for loading indicator and is throwing alerts when something goes wrong
// TOOD: when disconnecting from myspace check if user has non-empty password, so he is safely able to log back using email/password

function connectWithMyspace() {

    if (!wb.account.isReallyLoggedIn()) {
        // non-logged user was connected using myspace connect
        wb.dialog.showLoadingIndicator('#login');
        
        var complete = function(response) {
            if (response.statusCode == MSID.Connect.Enums.status.READY) {
                // try to login into transpond.com using myspace session
                var id = wb.wizard ? wb.wizard.id : false;
                wb.account.login('', '', id, function(){
                    wb.dialog.hideLoadingIndicator('#login');
                    wb.dialog.hide();
                    $('#notLoggedIn').addClass('hide');
                    $('#loggedIn').removeClass('hide');
                    if(wb.wizard){
                        wb.wizard.updatePreview();
                    } else {
                        // https://www.pivotaltracker.com/story/show/2169337
                        document.location = "/account";
                    }
                }, function(msg) {
                    if (msg=='No such account associated with current Facebook or MySpace session') {
                        // create account bound to this myspace user

                        wb.dialog.hide();
                        wb.dialog.show('#createAccountMS', {
                            closeOnClick: true,
                            closeOnEsc: true
                        });

                        $('#createAccountMS .dialog_title').html('Welcome to Webtrends Apps!');
                    } else {
                        if (!msg) msg = 'Unspecified error';
                        wb.dialog.hideLoadingIndicator('#login');
                        wb.dialog.showErrorMessage('#login', msg);
                    }
                }, 'myspace');
            } else {
                msg = 'Logging error';
                wb.dialog.showErrorMessage('#login', msg);
            }
        }
        
        MSID.Connect.requestLogin(function(response) {
            wb.dialog.hideLoadingIndicator('#login');
            // https://www.pivotaltracker.com/story/show/3539425
            if (response.statusCode == MSID.Connect.Enums.status.INVALID_SESSION_TOKEN) {
                console.log(response.statusCode);
                MSID.Connect.requestLogin(function(response2) {
                    complete(response2);
                });
            } else {
                complete(response);
            }
        }, 3000);
    } else {
        // logged user => associate myspace uid with this account
        var box = $('.myspace_association_box');

        MSID.Connect.requestLogin(function (response) {
            if (response.statusCode == MSID.Connect.Enums.status.READY) {
                $.ajax({
                    dataType: "json",
                    type: "POST",
                    url: '/transponder/account/reconnect_myspace',
                    success: function(data) {
                        if (data.success) {
                            var uid = $.cookie('myspaceid.friendid');
                            wb.account.setMyspaceUID(uid);

                            box.children().hide();
                            box.find('.myspace_associated').show();
                        } else {
                            if (data.errorMsg=='Facebook or MySpace user already associated with some other account.') {
                                alert('This MySpace user is already associated with different Transpond account.\n\nSolution: Please log into Transpond.com using this MySpace user and remove MySpace association from that other account. Then log back to this Transpond.com account and try again.');
                            } else {
                                alert(data.errorMsg || 'Problem communicating with server');
                            }
                        }
                    },
                    error: function(response) {
                        try {
                            var data = JSON.parse(response.responseText);
                        } catch (e) {
                            data = {
                                code: 666,
                                errorMsg: 'Malformed server response'
                            };
                        }
                        if (data.errorMsg=='Facebook or MySpace user already associated with some other account.') {
                            alert('This MySpace user is already associated with different Transpond account.\n\nSolution: Please log into Transpond.com using this MySpace user and remove MySpace association from that other account. Then log back to this Transpond.com account and try again.');
                        } else {
                            alert(data.errorMsg || 'Problem communicating with server');
                        }
                    }
                });
            } else {
                msg = 'Logging error';
                alert(msg);
            }
        }, 3000);
    }

    
//    MSID.Connect.tryConnect(handleResponse);    
}

function reconnectWithMyspace() {
    // need force logout from myspace, because user may be still logged in under old user
    // it is just safer to ask user again for his myspace credentials, than explaining it in the text
    
    $.cookie('myspaceid.signed', null);
    $.cookie('myspaceid.signature', null);
    $.cookie('myspaceid.friendid', null);
    $.cookie('myspaceid.session_token', null);
    $.cookie('myspaceid.request_token', null);
    $.cookie('myspaceid.identity', null);
    $.cookie('myspaceid.request_target', null);
    $.cookie('myspaceid.response_code', null);
    $.cookie('myspaceid.target_domain', null);
    
    connectWithMyspace();
}

function disconnectWithMyspace() {
    var box = $('.myspace_association_box');
    $.ajax({
        dataType: "json",
        type: "POST",
        url: '/transponder/account/disconnect_myspace',
        success: function(data) {
            if (data.success) {
                wb.account.clearMyspaceUID();
                box.children().hide();
                box.find('.myspace_association_removed').show();
            } else {
                alert('Problem communicating with server');
            }
        },
        error: function() {
            alert('Problem communicating with server');
        }
    });
}

function updateMyspaceAssociationBox() {
    var box = $('.myspace_association_box');
    box.children().hide();
    var uid = wb.account.getMyspaceUID();
    if (uid) {
        box.find('.myspace_associated').show();
    } else {
        box.find('.myspace_not_associated').show();
    }
}
