define('bitbucket/internal/feature/default-reviewers', [
    'aui',
    'chaperone',
    'jquery',
    'bitbucket/util/events',
    'bitbucket/util/navbuilder',
    'bitbucket/util/server',
    'bitbucket/util/state',
    'bitbucket/internal/util/analytics',
    'exports'
], function(
    AJS,
    Chaperone,
    $,
    events,
    nav,
    server,
    pageState,
    analytics,
    exports
) {
    'use strict';

    var $reviewerEl;
    var defaultReviewers;

    exports.init = function() {
        $reviewerEl = $('#reviewers');

        events.on("bitbucket.internal.feature.compare.form.state", function(formState) {
            if (formState.newForm === 'pullRequest') {
                refreshDefaultReviewers()
            }
        });

        var sourceBranch = pageState.getSourceBranch();
        var targetBranch = pageState.getTargetBranch();
        if (sourceBranch && targetBranch && sourceBranch.type.id === "branch" && targetBranch.type.id === "branch") {
            refreshDefaultReviewers();
        }

        $('#submit-form').on('click', function() {
            var submittedReviewers = $reviewerEl.data('select2').data();
            var totalReviewerCount = submittedReviewers.length;

            // Determine how many of the reviewers submitted are the default reviewers
            var defaultReviewersUsed = submittedReviewers.filter(function(reviewer) {
                return defaultReviewers.some(function(defaultReviewer) {
                    return reviewer.item.name === defaultReviewer.name;
                })
            });

            analytics.add('defaultreviewers.pullrequest.created', {
                'totalReviewers': totalReviewerCount,
                'defaultReviewers': defaultReviewers.length,
                'defaultReviewersUsed': defaultReviewersUsed.length
            });
        });
    };

    function setupFeatureDiscovery() {
        var metaEl = document.getElementById('default-reviewers-feature-discovery-meta');
        var isRepoAdmin = metaEl && metaEl.dataset.featureDiscoveryLevel === 'repo-admin';
        var content = AJS.I18n.getText('bitbucket.defaultreviewers.discovery.content');
        // for regular users also add the CTA to contact a repo admin to change the setting
        var speakToAdminCTA = AJS.I18n.getText('bitbucket.defaultreviewers.discovery.content.ask.for.change');
        var adminLink = {};

        if (isRepoAdmin) {
            // for admins add a link to the settings and remove the CTA to contact a repo admin
            adminLink = {
                url: nav.pluginServlets()
                    .path('default-reviewers')
                    .currentRepo()
                    .build(),
                urlText: AJS.I18n.getText('bitbucket.defaultreviewers.discovery.repo-admin.link.text')
            };
            speakToAdminCTA = '';
        }

        Chaperone.registerFeature('default-reviewers', [{
            id: 'default-reviewers-discovery',
            selector: '#s2id_reviewers',
            alignment: 'left middle',
            title: AJS.I18n.getText('bitbucket.defaultreviewers.discovery.user.title'),
            persistent: false,
            content: bitbucket.internal.page.defaultReviewers.common.featureDiscoveryContent({
                content: content + ' ' + speakToAdminCTA,
                url: adminLink.url,
                urlText: adminLink.urlText
            }),
            close: {
                text: AJS.I18n.getText("bitbucket.web.got.it")
            },
            moreInfo: {
                href: bitbucket_help_url('bitbucket.help.defaultreviewers.learn.more'),
                text: AJS.I18n.getText('bitbucket.defaultreviewers.learn.more'),
                extraAttributes: {
                    target: "_blank"
                }
            },
            width: 340,
            once: true
        }]);
    }

    function refreshDefaultReviewers() {
        var ERROR_ID = 'default-reviewers-error';
        $('#' + ERROR_ID).remove();

        var fromRepo = pageState.getSourceBranch().repository.id;
        var fromBranch = pageState.getSourceBranch().id;

        var toRepo = pageState.getTargetBranch().repository.id;
        var toBranch = pageState.getTargetBranch().id;

        if (fromRepo && fromBranch && toRepo && toBranch) {
            server.rest({
                url: nav.rest('default-reviewers', 'latest')
                    .currentRepo()
                    .addPathComponents('reviewers')
                    .build(),
                contentType: 'application/json',
                type: 'GET',
                data: {
                    sourceRepoId: fromRepo,
                    sourceRefId: fromBranch,
                    targetRepoId: toRepo,
                    targetRefId: toBranch
                }
            }).done(function(data) {
                var currentUserName = pageState.getCurrentUser().name;

                defaultReviewers = data && data.filter(function(el) {
                    return el.name !== currentUserName;
                });

                $reviewerEl.data('select2')
                    .data(defaultReviewers && defaultReviewers
                        .map(function(el) {
                            return {
                                id: el.name,
                                item: el
                            }
                        })
                    );

                if (defaultReviewers && defaultReviewers.length) {
                    setupFeatureDiscovery();
                }
            }).fail(function() {
                // if anything failed, show an error message
                $reviewerEl.after(
                    bitbucket.internal.page.defaultReviewers.common.errorMessage({
                        id: ERROR_ID,
                        message: AJS.I18n.getText('bitbucket.defaultreviewers.pullRequest.create.fetch.error')
                    })
                );
            });
        }
    }
});
