//Uses this instead: /sites/default/js/components/plugins/mtc_outofstocknotify/out_of_stock_notify.vue

Vue.component('out-of-stock-notify', {

    props: {
        urlSubmit: {
            type: String,
            default: null,
        },
        buttonLabel: {
            type: String,
            default: null,
        },
        shopItemId: {
            type: Number,
            default: null,
        },
    },


    data: function() {
        return {
            email: '',
            didSubmit: false,
            isBusy: false,
        }
    },


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

    computed: {

        isEmailValid: function() {
            let is_valid = false;

            // Super simple validation.
            if (this.email.length >= 5 && this.email.match(/^[^@]+@[^\.@]+\.[^\.@]+/)) {
                is_valid = true;
            }

            return is_valid;
        },

    },


    methods: {
        
        submitOutOfStockNotifyForm: function() {
            this.isBusy = true;

            this.$http.post(this.urlSubmit, {
                email: this.email,
                item_id: this.shopItemId,
            })
                .then(function (res) {
                    if (! res.data.errors) {
                        this.didSubmit = true;
                    }
                })
                .finally(function() {
                    this.isBusy = false;
                })
        },
        
    },

    template: `

    <section class="outOfStockNotifyWrapper">

        <div v-if="didSubmit">
            <p>Thank you.</p>
            <p>Your email has been registered and we will email you when the product is back in stock.</p>
        </div>

        <div v-else>
            <div class="row">
                <label for="quantity">Email address:</label>
                <input
                    name="email"
                    type="email"
                    placeholder="Email address"
                    v-model="email"
                />
            </div>

            <button
                type="submit"
                class="button"
                :disabled="(! isEmailValid) || isBusy"
                v-text="buttonLabel"
                @click="submitOutOfStockNotifyForm"
            >
            </button>
        </div>

    </section>

    `,

});
