define('bitbucket/internal/feature/comments/likes/analytics', [
    'bitbucket/util/events',
    'bitbucket/util/state',
    'bitbucket/internal/util/analytics',
    'bitbucket/internal/util/function',
    'exports'
],
function(
    events,
    pageState,
    analytics,
    fn,
    exports
) {

    'use strict';

    /**
     * Init the analytics so that it listens for like and unlike events.
     */
    function init() {
        events.on("bitbucket.internal.feature.comments.likes.like", triggerAnalyticsEvent.bind(null, 'like'));
        events.on("bitbucket.internal.feature.comments.likes.unlike", triggerAnalyticsEvent.bind(null, 'unlike'));
        events.on("bitbucket.internal.feature.comments.likes.actions.like", triggerAnalyticsEvent.bind(null, 'actions.like'));
    }

    var EVENT_PREFIX = 'comment.';

    /**
     * Trigger an analytics event
     *
     * @param {string} name - The name of the event to trigger will be appended to {@code EVENT_PREFIX}
     * @param {Object} likesInfo
     * @param {number} likesInfo.commentId - The comment that has been actioned.
     * @param {number} likesInfo.likerCount - The number of people who now like the comment.
     */
    function triggerAnalyticsEvent(name, likesInfo) {
        analytics.add(EVENT_PREFIX + name, analyticsAttributes(likesInfo));
    }

    /**
     * Generates an object of attributes to send with the analytics event
     *
     * @param likesInfo
     * @param {Object} likesInfo
     * @param {number} likesInfo.commentId - The comment that has been actioned.
     * @param {number} likesInfo.likerCount - The number of people who now like the comment.
     * @returns {object}
     */
    function analyticsAttributes(likesInfo){
        var pullRequest = pageState.getPullRequest();
        var repo = pageState.getRepository();

        var analyticsData = {
            "comment.id": likesInfo.commentId,
            "repository.id": repo.id,
            "totalLikes": likesInfo.likerCount
        };

        if (pullRequest) {
            var currentUserSlug = pageState.getCurrentUser().slug;
            var reviewerSlugs = pullRequest.reviewers.map(fn.dot('user.slug'));

            analyticsData.isAuthor = pullRequest.author.user.slug === currentUserSlug;
            analyticsData.isReviewer = reviewerSlugs.indexOf(currentUserSlug) !== -1;
            analyticsData['pullRequest.id'] = pullRequest.id;
        }

        return analyticsData;
    }

    exports.init = init;
});
