/**
 * clearFusionCMS Facebook helpers.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package clearFusionCMS
 * @copyright Copyright (c) 2016 clearFusionCMS. All rights reserved.
 * @link http://clearFusionCMS.com
 */

/**
 * Setup and run login/auth against Facebook.
 *
 * @param string selector Button selector.
 * @param string scope The access scope.
 * @param string connectedURI The URI to send the AJAX call to once the connection is made.
 * @param string emailMsg The message to show if email permission needed.
 */
function cfFacebookConnect(selector, scope, connectedURI, emailMsg) {

	/**
	 * Handle processing once a connection is made.
	 *
	 * @param Object response The Facebook response object.
	 */
	function onConnected(response) {
		$fl.ajax(
			connectedURI,
			{
				method: 'post',
				data: {
					fbAccessToken: response.authResponse.accessToken
				},
				dataType: 'json',
				async: true,
				success: function (data) {
					// If success
					if(data.success) {
						$fl('.login-with-facebook').css('display', 'none');

						if(data.redirect) {
							window.location.href = data.redirect;
						}
					}
					// else break the connection
					else {
						FB.api(
							"/me/permissions",
							"DELETE",
							function(response) {}
						);

						if(data.msg)
							alert(data.msg);
					}
				}
			}
		);
	}

	// Capture clicks
	$fl(selector).bind('click', function(e) {
		e.preventDefault();

		FB.login(function(response) {
				if(response.status == 'connected') {
					var connected = false;

					// If email required then check it's granted
					if(/email/.test(scope)) {

						// Test for email scope
						FB.api('/me?fields=id,name,email', function(meResponse) {
							// If email permission granted then hand off to the server
							if(meResponse.email) {
								onConnected(response);
							}
							// No email so tell user and kill the link to Facebook
							else {
								// Force disconnect from FB
								FB.api(
									"/me/permissions",
									"DELETE",
									function(response) {}
								);

								alert(emailMsg);
							}
						});

					}
					else {
						onConnected(response);
					}
				}
			},
			{ scope: scope }
		);
	});
}
