<template>
    <form class="pure-form pure-form-aligned">
        <fieldset>
            <div class="pure-control-group">
                <label for="topic">Catégorie :</label>
                <select v-model="topic" v-on:change="selectTopic" id="topic">
                    <option v-for="template in topics" :value="template" :key="template">
                        {{ template }}
                    </option>
                </select>
            </div>
            <div class="pure-control-group">
                <label for="subject">Sujet :</label>
                <select v-model="selected" v-on:change="selectEmail" v-bind="topic === null">
                    <option v-for="template in emails" :value="template.slug" :key="template.slug">
                        {{ template.name }}
                    </option>
                </select>
            </div>
            <div v-if="email != null">
                <h4 class="email-subject">Sujet : {{ email.subject }}</h4>
                <nl2br tag="p" :text="email.body" class-name="email-body"></nl2br>
            </div>
        </fieldset>
    </form>
</template>

<script>
    import Vue from 'vue';
    import VueResource from 'vue-resource';
    import Nl2br from 'vue-nl2br';

    Vue.component('nl2br', Nl2br);
    Vue.use(VueResource);

    export default {
        name: "EmailModel",
        components: {
            Nl2br
        },
        data: function() {
            return {
                emails: [],
                selected: "",
                email: null,
                topics: [],
                topic: null
            }
        },
        beforeCreate() {
            let $this = this;
            Vue.http.get("topics.php").then(response => {
                $this.topics = response.body
            });
        },
        methods: {
            selectTopic: function() {
                let $this = this;
                Vue.http.post("emails.php", {"topic": $this.topic}).then(response => {
                    $this.emails = response.body;
                });
            },
            selectEmail: function() {
                let $this = this;
                Vue.http.post("email.php", {"topic": $this.topic, "slug": $this.selected}).then(response => {
                    $this.email = response.body;
                });
            }
        }
    }
</script>

<style scoped>
    .pure-control-group {
        text-align: left;
    }
    .email-subject, .email-body {
        text-align: left;
    }
</style>