define('bitbucket/internal/feature/sync/button/ref-sync-button', [
    'jquery',
    'bitbucket/util/navbuilder',
    'bitbucket/internal/feature/sync/dialog/ref-sync-dialog',
    'bitbucket/internal/model/page-state',
    'bitbucket/internal/util/ajax',
    'bitbucket/internal/util/events',
    'exports'
], function(
    $,
    nav,
    RefSyncDialog,
    pageState,
    ajax,
    events,
    exports
) {
    'use strict';

    var syncButtonSelector = '.synchronize-ref';

    function getSyncUrl() {
        return nav.newBuilder([
            'rest', 'sync', 'latest', 'projects', pageState.getProject().getKey(),
            'repos', pageState.getRepository().getSlug()
        ]).build();
    }

    function checkSynchronized(revisionReference) {
        ajax.rest({
            url: getSyncUrl(),
            data: {
                at: revisionReference.getId()
            }
        }).done(function(syncData) {
            // if data is null, then branch is in-sync
            // we only want to show manual synchronize button if branch has diverged
            var diverged = syncData && syncData.state === 'DIVERGED';
            $(syncButtonSelector).toggleClass('hidden', !diverged);
        });
    }

    exports.onReady = function() {
        var refSyncDialog = new RefSyncDialog();

        $(syncButtonSelector).on('click', function(e) {
            e.preventDefault();
            refSyncDialog.showFor(pageState.getRevisionRef());
        });

        checkSynchronized(pageState.getRevisionRef());
        events.on('bitbucket.internal.layout.branch.revisionRefChanged', checkSynchronized);
    };
});

jQuery(document).ready(function() {
    require('bitbucket/internal/feature/sync/button/ref-sync-button').onReady();
});