<template>
    <div class="list-group">
        <a v-for="annotation in annotations"
            ref="annotations"
            @click="toggleAnnotation($event, annotation)"
            :href="getAnnotationURL(annotation.annotation_guid)"
            class="list-group-item"
            v-bind:class="{ active: isActive(annotation) }">
            <h3 class="small list-group-item-heading">
                {{ annotation.title }}
            </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',
            'annotationUrl'
        ],
        mounted() {
            if (this.annotation) {
                this.slideToAnnotation();
            }
        },
        watch: {
            annotation: function(annotation) {
                if (annotation) {
                    this.slideToAnnotation();
                }
            }
        },
        methods: {
            getAnnotationURL: function(guid) {
                return this.annotationUrl.replace(':annotation_guid', guid);
            },
            toggleAnnotation: function(e, annotation) {
                e.preventDefault();
                if (this.annotation && this.annotation === annotation) {
                    this.$emit('close:annotation');
                } else {
                    this.$emit('click:annotation', 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.getAnnotationURL(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>
