define('bitbucket/internal/feature/branch-deletion', [
    'aui',
    'jquery',
    'lodash',
    'bitbucket/util/navbuilder',
    'bitbucket/internal/model/page-state',
    'bitbucket/internal/util/ajax',
    'bitbucket/internal/util/events',
    'bitbucket/internal/util/shortcuts',
    'bitbucket/internal/widget/confirm-dialog',
    'exports'
], function (
    AJS,
    $,
    _,
    nav,
    pageState,
    ajax,
    events,
    shortcuts,
    ConfirmDialog,
    exports
) {
    'use strict';

    var linkSelector = '.delete-branch';

    function createConfirmationDialog() {
        var dialog = new ConfirmDialog({
            id : 'delete-branch-dialog',
            titleText: AJS.I18n.getText('bitbucket.feature.branch-deletion.dialog.title'),
            titleClass : 'warning-header',
            panelContent : bitbucket.internal.feature.branchDeletion.dialog(),
            submitText : AJS.I18n.getText('bitbucket.web.button.delete'),
            submitToHref : false
        });

        dialog.addConfirmListener(function(promise, $trigger, removeDialog, dialog, $spinner) {
            var branchId = getBranchData($trigger, 'id');
            var branchDisplayId = getBranchData($trigger, 'display-id');
            var latestCommit = getBranchData($trigger, 'latest-commit');
            $spinner.show();
            deleteBranchByRest(branchDisplayId, latestCommit).done(function() {
                events.trigger('bitbucket.internal.page.branches.revisionRefRemoved', null, {
                    id: branchId,
                    displayId: branchDisplayId,
                    latestCommit: latestCommit
                });
            }).fail(function (xhr, textStatus, errorThrown, data) {
                addErrorNotifications(data && data.errors);
            }).always(removeDialog);
        });

        dialog.attachTo(linkSelector, function(trigger, dialog) {
            var branchName = getBranchData(trigger, 'display-id');
            dialog.getCurrentPanel().body.find('.branch-name').text(branchName);

            //the href is of the form #<ahead number>
            var ahead = parseInt($(trigger).attr('href').substring(1), 10);
            if (ahead > 0) {
                var baseRefDisplayId = pageState.getRevisionRef().get('displayId');
                dialog.getCurrentPanel().body.append(bitbucket.internal.feature.branchDeletion.aheadWarning({
                    ahead: ahead,
                    baseRefDisplayId: baseRefDisplayId
                }));
            }


        }, document);
    }

    function deleteBranchByRest(branchName, latestCommit) {
        return ajax.rest({
            url: getBranchRestUrl(),
            type: 'DELETE',
            data: {
                name : branchName,
                endPoint : latestCommit
            },
            statusCode : {
                '400' : false,
                '403' : false,
                '409' : false
            }
        });
    }

    function getBranchData(trigger, dataKey) {
        var attr = 'data-' + dataKey;
        return $(trigger).closest('[' + attr + ']').attr(attr);
    }

    function getBranchRestUrl() {
        return nav.rest('branch-utils')
            .project(pageState.getProject().getKey())
            .repo(pageState.getRepository().getSlug())
            .addPathComponents('branches').build();
    }

    function addErrorNotifications(errors) {
        if (errors && errors.length > 0) {
            var errorBody = "";
            _.forEach(errors, function(error) {
                errorBody += bitbucket.internal.widget.errorContent(error);
            });
            require(['aui/flag'], function(flag) {
                flag({
                    type: 'error',
                    body: errorBody
                });
            });
        }
    }

    exports.onReady = function () {
        createConfirmationDialog();

        shortcuts.bind('branchlist.deleteBranch', function() {
            $('#branch-list tr.focused .delete-branch').click();
        });
    };
});

jQuery(document).ready(function () {
    require('bitbucket/internal/feature/branch-deletion').onReady();
});
