<template>
    <div class="list-group">
        <a v-for="annotation in annotations"
            ref="annotations"
            @click="onAnnotationClick($event, annotation)"
            :href="'#' + annotation.annotation_guid"
            class="list-group-item"
            v-bind:class="{ active: isActive(annotation) }">
            <h3 class="small list-group-item-heading">
                {{ annotation.title }}
                <button type="button" class="close" data-dismiss="alert" aria-label="Close" @click="onAnnotationClose">
                    <span aria-hidden="true">&times;</span>
                </button>
            </h3>
            <p class="list-group-item-text" v-for="tag in annotation.tags">{{ tag.tag_label }}</p>
            <div class="list-group-item-footer">
              <i class="fa fa-comment"></i> {{ getCommentsCount(annotation) }}
            </div>
        </a>
    </div>
</template>

<script>

    import _ from 'lodash';

    export default {
        props: [
            'annotations',
            'annotation'
        ],
        mounted() {
            if (this.annotation) {
                this.slideToAnnotation();
            }
        },
        watch: {
            annotation: function(annotation) {
                if (annotation) {
                    this.slideToAnnotation();
                }
            }
        },
        methods: {
            onAnnotationClick: function(e, annotation) {
                e.preventDefault();
                this.$emit('click:annotation', annotation);
            },
            onAnnotationClose: function(e) {
                e.preventDefault();
                e.stopPropagation();
                this.$emit('close:annotation');
            },
            isActive: function(annotation) {
                return annotation === this.annotation;
            },
            getCommentsCount: function(annotation) {
                var commentsCount = annotation.stats.comments_count;
                return commentsCount + ' commentaire' + (commentsCount > 1 ? 's' : '');
            },
            slideToAnnotation: function() {
                var el = _.find(this.$refs.annotations, (el) => {
                    return $(el).attr('href') === ('#' + this.annotation.annotation_guid);
                });
                if (el) {
                    var $container = $(this.$el.closest('.panel'));
                    $container.animate({
                        scrollTop: $container.scrollTop() - $container.offset().top + $(el).offset().top
                    }, 600);
                }
            }
        }
    }

</script>

<style scoped>

</style>
