/**
 * Shared utility methods for all lightning components in the package.
 * Thanks to https://salesforce.stackexchange.com/questions/136760/static-resource-in-lighting-component/136762#136762
 */
(function(w){
    "use strict"; // Optional because LC on LockerService active runs in strict mode.

    var communityHubLightningUtilMethods = {
        'handleUnsuccessfulResponse': handleUnsuccessfulResponse,
        'rejectUnsuccessfulResponsePromise': rejectUnsuccessfulResponsePromise,
        'handleRejectedPromise': handleRejectedPromise
    };

    /**
     * Handles any response other than unsuccessful ones coming from an Apex controller.
     * @param {object} response - The unsuccessful response.
     */
    function handleUnsuccessfulResponse(error, friendlyMessage) {
        throw(friendlyMessage);
    }

    /**
     * Handles any response other than unsuccessful ones coming from an Apex controller rejecting a promise.
     * @param {object} response - The unsuccessful response.
     */
    function rejectUnsuccessfulResponsePromise(response, reject) {
        var state = response.getState();

        if (state === 'ERROR') {
             var errors = response.getError();

             if (errors && errors[0] && errors[0].message) {
                 reject(Error(errors[0].message));
             } else {
                 reject(Error('Unknown error'));
             }
         } else {
             reject(Error('Unknown error'));
         }
    }

    /**
     * Handles a rejected promise similarly to how a response error is handled.
     * @param {object} error - The error message.
     */
    function handleRejectedPromise(error) {
        // Log the real error.
        console.log('Error handled: ' + error);

        var toastEvent = $A.get('e.force:showToast');

        toastEvent.setParams({
            'type': 'error',
            'title': 'Error',
            'message': 'Something has gone wrong. Please contact support if you continue to receive this error.'
        });

        // Show the user a friendly error.
        toastEvent.fire();
    }

    w.ncLightningUtil = communityHubLightningUtilMethods;
})(window);