Vue.component('patientTreatmentPlan', {

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

    data: function() {
        return {
            treatments: [],
            loading: false,
            add: false,
            showAll: false,
            eventIndex: 0,
        };
    },

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

    computed: {
        canLoadAll() {
            return this.treatments.length > 1 && !this.showAll;
        },
        activeTreatment() {
            if (!this.treatments.length) {
                return null;
            }
            for (let i = 0; i < this.treatments.length; i++) {
                if (this.treatments[i].status === 'active') {
                    return this.treatments[i];
                }
            }
            return null;
        },
    },

    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 === 'treatmentSaved') {
                    this.load();
                }
                if (event.name === 'treatmentDeleted') {
                    this.load();
                }
            }
            // Update event index so that we don't process already processed events
            this.eventIndex = stack.length;
        }
    },

    methods: {
        init() {
            this.load();
        },
        editTreatmentAction(treatment) {
            if (typeof treatment === 'undefined') {
                treatment = defaultTreatment;
            }
            this.emitEvent('initEditTreatment', {
                treatment: treatment,
            })
        },
        cancel() {
            this.add = false;
        },
        load() {
            let vm = this;

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

                    const data = response.data;

                    vm.treatments = data.treatments;
                    vm.loading = false;
                    vm.emitEvent('treatmentsLoaded');
                });
        },
        loadAll() {
            this.showAll = true;
        },
        emitEvent(name, data) {
            this.$parent.emitEvent(name, data)
        },
    },
});
