// this file contains main Facebook Connect logic

// Workflow
// *** read http://wiki.developers.facebook.com/index.php/Connect/Authentication_and_Authorization
// ------------------------------------------------------------
// 1. Temporary user, on login dialog:
//   a) show "connect with facebook" button
//      when user clicks it, it performs scenario 1,2 or 3 from ***
//      after authorized user comes back from facebook:
//      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 Facebook
//        -> when user creates account this way, make it associated with Facebook 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 facebook => show "reconnect" and "disconnect" actions
//    b) if account is not connected => show "connect with facebook" button
//       when user clicks it, it performs scenario 1,2 or 3 from ***
//       after authorized user comes back from facebook:
//       * assign this facebook user to this account
//    
//    reconnect action works similar to b) but first forces logout from facebook (it is just safer to ask user again for his facebook credentials, than explaining it in the text)
//    disconnect action simply removes facebook 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 facebook check if user has non-empty password, so he is safely able to log back using email/password

function connectedUserCallback() {
    if (!wb.account.isReallyLoggedIn()) {
        // non-logged user was connected using facebook connect
        wb.dialog.showLoadingIndicator('login');
        
        // try to login into transpond.com using facebook 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 session') {
                // create account bound to this facebook user
                var api = FB.Facebook.apiClient;
                var uid = api.get_session().uid;
                api.users_getInfo(uid, ['first_name', 'last_name'], function(data) {
                    wb.dialog.hideLoadingIndicator('login');

                    wb.dialog.hide();
                    wb.dialog.show('createAccountFB');

                    $('#createAccountFB .dialog_title').html('Welcome to Transpond, '+data[0]['first_name']+'!');
                });
            } else {
                if (!msg) msg = 'Unspecified error';
                wb.dialog.hideLoadingIndicator('login');
                wb.dialog.showErrorMessage('login', msg);
            }
        });
    } else {
        // logged user => associate facebook uid with this account
        var box = $('.facebook_association_box');
        $.ajax({
            dataType: "json",
            type: "POST",
            url: '/transponder/account/reconnect',
            success: function(data) {
                if (data.success) {
                    
                    // we need to refresh account's facebook UID
                    // see https://www.pivotaltracker.com/story/show/1814821
                    var api = FB.Facebook.apiClient;
                    var uid = api.get_session().uid;
                    wb.account.setFacebookUID(uid);
                    
                    box.children().hide();
                    box.find('.facebook_associated').show();
                } else {
                    if (data.errorMsg=='Facebook user already associated with other account.') {
                        alert('This Facebook user is already associated with different Transpond account.\n\nSolution: Please log into Transpond.com using this Facebook user and remove Facebook 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 user already associated with other account.') {
                    alert('This Facebook user is already associated with different Transpond account.\n\nSolution: Please log into Transpond.com using this Facebook user and remove Facebook association from that other account. Then log back to this Transpond.com account and try again.');
                } else {
                    alert(data.errorMsg || 'Problem communicating with server');
                }
            }
        });
    }
}

function connectWithFacebook() {
    FB.Connect.requireSession(connectedUserCallback);
}

function reconnectWithFacebook() {
    // need force logout from facebook, because user may be still logged in under old user
    // it is just safer to ask user again for his facebook credentials, than explaining it in the text
    FB.Connect.logout(function() {
        FB.Connect.requireSession(connectedUserCallback);
    });
}

function disconnectWithFacebook() {
    var box = $('.facebook_association_box');
    $.ajax({
        dataType: "json",
        type: "POST",
        url: '/transponder/account/disconnect',
        success: function(data) {
            if (data.success) {
                wb.account.clearFacebookUID();
                box.children().hide();
                box.find('.facebook_association_removed').show();
            } else {
                alert('Problem communicating with server');
            }
        },
        error: function() {
            alert('Problem communicating with server');
        }
    });
}

function updateFacebookAssociationBox() {
    var box = $('.facebook_association_box');
    box.children().hide();
    var uid = wb.account.getFacebookUID();
    if (uid) {
        box.find('.facebook_associated').show();
    } else {
        box.find('.facebook_not_associated').show();
    }
}

function requireFacebookLogin(successFn, failureFn, userHint) {
    FB.Connect.requireSession(successFn, failureFn, userHint);
}