// Default file size limit, in megabytes.
var DEFAULT_LIMIT = 2;
var MEGABYTES_TO_BYTES_MULTIPLIER = 1000000;

/**
 * @description Plugin syntax for jQuery.
 */
(function ($) {
    /**
     * @description Sets plugin namespace for method calling.
     *              Eg. $('#myDiv').nuValidateInputFile();
     * @param userOptions Optional options that can be passed in by whatever is calling this.
     */
    $.fn.nuValidateInputFile = function(userOptions) {
        var options = $.extend({}, $.fn.nuValidateInputFile.defaults, userOptions);

        // If there are no files, disable the upload button if present.
        if (this[0].files === undefined || this[0].files.length === 0) {
            disableOrEnableUploadButton(options.uploadButton, false);
        }

        this.on('change', function(e) {
            var valid = true;

            // Calculate the file size limit in bytes.
            var limit = options.limit * MEGABYTES_TO_BYTES_MULTIPLIER;

            // Check if the file size is over the limit.
            if (this.files[0].size > limit) {
                valid = false;
            }

            // Enable or disable the upload button based on whether or not the file is valid.
            disableOrEnableUploadButton(options.uploadButton, valid);

            // Show or hide the error element based on whether or not the file is valid.
            showOrHideErrorElement(options.errorElement, valid);

            // If a callback function was specified, call it with a response.
            if (options.onValidate !== undefined && typeof options.onValidate === 'function') {
                var response = {
                    isValid: valid
                };

                options.onValidate(response);
            }
        });

        return this;
    };

    // Plugin defaults. The defaults as a property allow easier manipulation outside of the plugin itself.
    $.fn.nuValidateInputFile.defaults = {
        limit: DEFAULT_LIMIT
    };

    /**
     * @description Disables or enables the upload button depending on if the validation passed.
     * @param valid A boolean for whether or not the file is valid.
     */
    function disableOrEnableUploadButton(uploadButton, valid) {
        if (uploadButton !== undefined) {
            uploadButton.prop('disabled', !valid);
        }
    }

    /**
     * @description Shows or hides the error element depending on if the validation passed.
     * @param valid A boolean for whether or not the file is valid.
     */
    function showOrHideErrorElement(errorElement, valid) {
        if (errorElement !== undefined) {
            if (valid) {
                errorElement.hide();
            } else {
                errorElement.show();
            }
        }
    }
}(jQuery));