<template>

    <section class="checkboxList">

        <div class="highlightBox" v-text="title"></div><!-- .Highlight Box -->


        <div class="checkboxListWrap">

            <div class="row" v-for="(option, optionIndex) in options">

                <div class="inputWrap">

                    <input
                            type="checkbox"
                            :id="'option_' + optionIndex"
                            v-model="options[optionIndex].is_selected"
                            @change="populateSelectedOptions()"
                    >
                    <label :for="'option_' + optionIndex">
                        <span v-html="option.label"></span>
                    </label>

                </div> <!-- .inputWrap -->

            </div> <!-- .error -->

        </div>


    </section>

</template>



<script>



export default {

    props: [
        "title",
        "urlGetAvailableOptions",
        "selectedOptions",
    ],


    data: function() {
        return {
            options: []
        }
    },


    created: function () {
        this.fetchAvailableOptions();
    },


    methods: {

        fetchAvailableOptions: function() {
            this.$http.get(this.urlGetAvailableOptions, {
                //
            })
            .then(function (res) {
                if (res.data.options) {
                    this.options = res.data.options;

                    for (let i = 0; i < res.data.options.length; i++) {
                        this.options[i].is_selected = false;
                        for (let j = 0; j < this.selectedOptions.length; j++) {
                            if (this.options[i].id == this.selectedOptions[j].id) {
                                this.options[i].is_selected = true;
                                break;
                            }
                        }
                    }
                }
            });
        },


        populateSelectedOptions: function() {

            while (this.selectedOptions.length) {
                this.selectedOptions.pop();
            }

            for (let i = 0; i < this.options.length; i++) {
                if (this.options[i].is_selected) {
                    this.selectedOptions.push(this.options[i]);
                }
            }

        },

    }
}

</script>
