<script>
import axios from "axios";

export default {
    props: {
        caracteristica: Object
    },
    data() {
        return {
            gdc: undefined
        }
    },
    watch: {
        '$root.gdc' : {
            handler(newValue) {
                if (newValue) {
                    this.gdc = newValue;
                    this.obtenerValor();
                }
            }
        },
    },
    methods: {
        toggleActivacion() {
            const id = this.caracteristica.id;
            axios.post(`/api/grupos-de-compra/${this.gdc}/${id}`)
                .then(response => {
                    this.caracteristica.habilitada = response.data[id];
                    this.$root[id] = response.data[id];
                });
        },
        obtenerValor() {
            const id = this.caracteristica.id;
            axios.get(`/api/grupos-de-compra/${this.gdc}/${id}`)
                .then(response => {
                    this.caracteristica.habilitada = response.data[id];
                    this.$root[id] = response.data[id];
                });
        },
    },
    mounted() {
        if (this.$root.gdc) {
            this.gdc = this.$root.gdc;
            this.obtenerValor();
        }
    }
}
</script>

<template>
    <tr>
        <td>{{ caracteristica.nombre }}</td>
        <td>
            <div class="field">
                <input type="checkbox" class="switch is-rounded is-success"
                       :id="'switch-'+caracteristica.id"
                       :checked="caracteristica.habilitada"
                       @change="toggleActivacion(caracteristica)">
                <label :for="'switch-'+caracteristica.id">
                    <span class="is-hidden-mobile">{{ caracteristica.habilitada ? 'Habilitada' : 'Deshabilitada' }}</span>
                </label>
            </div>
        </td>
    </tr>
</template>

<style scoped>

</style>
