define('bitbucket/internal/feature/readme/filecontent', [
    'aui',
    'jquery',
    'lodash',
    'bitbucket/internal/feature/readme/common',
    'bitbucket/internal/util/ajax',
    'bitbucket/internal/util/syntax-highlight'
], function (
    AJS,
    $,
    _,
    common,
    ajax,
    syntaxHighlight
) {

    return function(options) {
        if (options.contentMode !== 'source') {
            return null;
        }
        var fileChange = options.fileChange;
        return common.DATA.then(function(data) {
            var ext = fileChange.path.extension.toLowerCase();
            if (ext && _.contains(data.extensions, ext) && !_.contains(data.extensionsRaw, ext)) {
                var until = fileChange.commitRange.untilRevision.id;
                return ajax.rest({
                    // Note that we're using the commit instead of the blob, which is still unique but sadly won't hit
                    // the same browser cache as the request on the file page
                    url: common.createUrl(fileChange.path.components, until, until),
                    dataType:'html',
                    statusCode: {
                        '413': function() {
                            return $.Deferred().reject(AJS.I18n.getText('bitbucket.web.repo.readme.toolarge.detail'));
                        }
                    }
                }).then(function(html) {
                    options.$container.empty().append(
                        common.updateLinks($(bitbucket.internal.feature.readme.renderMarkup({content: html})))
                    );
                    syntaxHighlight.container(options.$container);
                    // Need to return _something_ to stop at this file-handler
                    // We don't have any events to destroy()
                    return {};
                });
            }
            return $.Deferred().reject();
        });
    };
});

require('bitbucket/feature/files/file-handlers').register({
    weight: 3000,
    handle: function (options) {
        return require('bitbucket/internal/feature/readme/filecontent').apply(this, arguments);
    }
});
