define('bitbucket/internal/page/settings/ref-sync-settings', [
    'jquery',
    'bitbucket/internal/feature/sync/common/ref-sync-common',
    'bitbucket/internal/feature/sync/dialog/ref-sync-dialog',
    'bitbucket/internal/model/rejected-revision-reference',
    'bitbucket/internal/widget/submit-spinner',
    'exports'
], function(
    $,
    refSyncCommon,
    RefSyncDialog,
    RejectedRevisionReference,
    SubmitSpinner,
    exports
) {
    'use strict';

    var syncButtonSelector = '.synchronize-ref';

    exports.onReady = function(checkBoxSelector) {
        var refSyncDialog = new RefSyncDialog();
        var $checkbox = $(checkBoxSelector);
        var checkboxSpinner = new SubmitSpinner($checkbox.next('label'));

        $checkbox.on('change', function() {
            var enable = this.checked;
            checkboxSpinner.show();

            // Todo: abort first promise if checkbox is clicked twice fast.
            refSyncCommon.enableRefSyncing(enable).done(function(syncStatus) {
                if (enable) {
                    $checkbox.closest('form').after(bitbucket.internal.feature.sync.refSyncStatus({syncStatus: syncStatus}));
                } else if (!syncStatus.available) {
                    window.location.reload();
                } else {
                    $('.sync-status').remove();
                }
            }).fail(function() {
                $checkbox.prop('checked', !enable); // revert checkbox
            }).always(function() {
                checkboxSpinner.hide();
            });
        });

        $(document).on('click', syncButtonSelector, function() {
            var ref = new RejectedRevisionReference($(this).closest('.diverged-ref').data('ref'));
            refSyncDialog.showFor(ref);
        });
    };
});