Vue.component('qualifying-answers-manager', {

    props: [
        "questions",
        "answers",
        "saveDataUrl",
        "itemId",
        "groups",
        "groupsConfig",
    ],

    data: function() {
        return {
            isBusy: false,
            groups_data: [],
            groups_config_data: {},
            logicLabels: [],
            answers_data: {},
        };
    },


    created: function() {

        this.groups_data = this.groups;

        this.groups_config_data = this.groupsConfig;

        this.logicLabels = [
            { id: 'and', label: '<strong>and</strong>', hex_rgb: '#f9f9f9' },
            { id: 'or', label: 'or', hex_rgb: '#f9f9f9' },
        ];

        this.logicLabelsUC = [
            { id: 'and', label: '<strong>AND</strong>', hex_rgb: '#f9f9f9' },
            { id: 'or', label: 'OR', hex_rgb: '#f9f9f9' },
        ];

        this.answers_data = this.answers;

    },


    computed: {

        numberOfGroupsInUse: function() {

            let group_ids = [];
            for (const questionId in this.answers_data) {
                let temp_group_id = this.answers_data[questionId].group_id;

                if (group_ids.indexOf(temp_group_id) < 0) {
                    group_ids.push(temp_group_id);
                }
            }

            return group_ids.length;

        },


        logicFormula: function() {

            let formula = '';
            let group_formulas = [];

            for (let g = 0; g < this.groups.length; g++) {

                let temp_group = {
                    elements: [],
                    logic: this.groups[g].logic,
                    hex_rgb: this.groups[g].hex_rgb
                };

                for (let q = 0; q < this.questions.length; q++) {
                    let questionId = this.questions[q]['Question ID'];

                    if (this.answers_data[questionId].group_id == this.groups[g].id) {
                        temp_group.elements.push("<strong style='color:" + temp_group.hex_rgb + "'>Q" + questionId +"</strong>");
                    }
                }

                if (temp_group.elements.length) {
                    group_formulas.push(" ( " + temp_group.elements.join(" <small>" + temp_group.logic + "</small> ") + " ) ");
                }

            }

            formula = group_formulas.join("<small>" + this.groups_config_data.logic.toUpperCase() + "</small>");

            return formula;

        },

    },


    methods: {

        getGroupIndex: function(question_row) {
            let group_index = undefined;

            let group_id = this.answers_data[question_row['Question ID']].group_id;

            for (let i = 0; i < this.groups_data.length; i++) {
                if (this.groups_data[i].id == group_id) {
                    group_index = i;
                    break;
                }
            }

            return group_index;
        },


        saveAnswer: function() {
            var that = this;

            let submit_data = {
                answers: this.answers_data,
                groups: this.groups_data,
                groups_config: this.groups_config_data,
            };

            this.isBusy = true;

            fetch(this.saveDataUrl, {
                method: 'POST',
                body: JSON.stringify(submit_data),
                headers: {
                    'Content-Type': 'application/json'
                },
            })
            .then(response => response.json())
            .then(data => {
                that.isBusy = false;
            });
        },

    },


    template: `
        <section>

            <table class="manage-items">

                <thead>
                    <tr style="font-size: 1.1em">
                        <th>Formula:</th>
                        <td colspan="5" v-html="logicFormula" style="border: 0px"></td>
                    </tr>
                    <tr>
                        <th>ID</th>
                        <th>Question</th>
                        <th>Possible Answers</th>
                        <th>Qualifying Answer</th>
                        <th>Group</th>
                        <th>Relationship within group</th>
                    </tr>
                </thead>

                <tbody class="tabular">
                    <tr v-for="question_row in questions">
                        <td v-text="question_row['Question ID']"></td>
                        <td v-text="question_row['Question']"></td>
                        <td v-text="question_row['Question Possible Answers']"></td>
                        <td>
                            <select
                                v-if="question_row['possible_answers_array'].length > 0"
                                class="js-qualifying-answer-save"
                                :multiple="!!question_row['Question Is Multi']"
                                v-model="answers[question_row['Question ID']].qualifying_answer"
                            >
                                <option value="">--- select ---</option>
                                <option
                                    v-for="possible_answer in question_row['possible_answers_array']"
                                    :value="possible_answer"
                                    v-text="possible_answer"
                                ></option>
                            </select>

                            <input
                                v-else
                                type="text"
                                v-model="answers[question_row['Question ID']].qualifying_answer"
                                class="js-qualifying-answer-save"
                            />
                        </td>
                        <td>
                            <toggle-button
                                v-model="answers_data[question_row['Question ID']].group_id"
                                :values="groups_data"
                            ></toggle-button>
                        </td>
                        <td>
                            <toggle-button
                                v-model="groups_data[getGroupIndex(question_row)].logic"
                                :values="logicLabels"
                            ></toggle-button>
                        </td>
                    </tr>
                </tbody>

                <tfoot v-if="numberOfGroupsInUse > 1">
                    <tr>
                        <th colspan="4" style="text-align: right">Relationship between groups:</th>
                        <td style="border-bottom: 0px">
                            <toggle-button
                                v-model="groups_config_data.logic"
                                :values="logicLabelsUC"
                            ></toggle-button>
                        </td>
                        <th></th>
                    </tr>

                </tfoot>

            </table>


            <div class="row">
                <button
                    @click.prevent="saveAnswer"
                    class="btn btn-secondary"
                    v-text="isBusy ? 'Saving...' : 'Save answers'"
                    :disabled="isBusy"
                ></button>
            </div>

        </section>
    `,

});
