Vue.component('patientReviews', {

    props: [
        'routes',
        'events',
        'patientData',
    ],

    data: function() {
        return {
            patient: {},
            reviews: [],
            types: [],
            mediums: [],
            loading: false,
            display: 5,
            eventIndex: 0,
            component: 'reviews',
        };
    },

    mounted: function() {
        this.init();
    },

    computed: {
        canLoadMore() {
            if (!this.reviews.length) {
                return false;
            }
            return this.reviews.length > this.display;
        }
    },

    watch: {
        events(stack) {
            // Because there may be more than one event at a time, loop through new events
            for (let i = this.eventIndex; i < stack.length; i++) {
                let event = stack[i];
                if (event.name === 'reviewsUpdated') {
                    this.load();
                }
            }
            // Update event index so that we don't process already processed events
            this.eventIndex = stack.length;
        }
    },

    methods: {
        init() {
            this.patient = this.patientData;
            this.load();
        },
        load() {
            this.loading = true;
            let vm = this;

            this.$http.post(this.routes['admin-reviews-load'], [])
                .then((response) => {

                    const data = response.data;

                    vm.reviews = data.reviews;
                    vm.loading = false;
                    vm.emitEvent('reviewsLoaded');
                });
        },
        loadMore() {
            this.display += 5;
            this.emitEvent('reviewsLoaded');
        },
        editReviewAction(id) {
            this.emitEvent('initReview', {
                reviewId: id > 0 ? id : null,
            });
        },
        emitEvent(name, data) {
            this.$parent.emitEvent(name, data);
        },
    },
});
