<template>
    <h3 class="text-center">Message Templates</h3>
    <ul>
        <li v-for="template in messageTemplates" :key="template.id">
            <b>{{ template.name }}</b><br>
            <FormatedText :value="template.message" :format="formatText" class="template-message"
                          @input="changeMessageTemplate(template.id, $event)"/>
        </li>
    </ul>
    <h3 class="text-center">Message Template Variables</h3>
    <ul>
        <li v-for="(variable, key) in messageTemplateVariables" :key="key">
            {{ variable }}
        </li>
    </ul>
</template>

<script>
import {mapActions, mapState} from 'vuex';
import Table from '@/components/Table';
import FormatedText from "@/components/inputs/FormatedText.vue";

export default {
    name: 'Settings',
    components: {FormatedText, Table},
    computed: mapState(['messageTemplates', 'messageTemplateVariables']),
    methods: {
        ...mapActions(['fetchMessageTemplates', 'fetchMessageTemplateVariables']),
        formatText(value) {
            return value.replace(/{{(.+?)}}/g, (match, key) => {
                return `<span class="text-primary">{{${key}}}</span>`;
            }).replace(/\n/g, '<br>').replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;');
        },
        changeMessageTemplate(id, message) {
            console.log(id, message);
            this.messageTemplates.forEach(template => {
                if (template.id === id) {
                    template.message = message;
                }
            });
        }
    },
    mounted() {
        this.fetchMessageTemplates();
        this.fetchMessageTemplateVariables();
    },
};
</script>

<style scoped>
pre {
    white-space: pre-wrap;
    word-wrap: break-word;
    color: inherit;
}

.template-message {
    border: none;
    margin-left: 8em;
    white-space: pre-wrap;
    word-wrap: break-word;
}
</style>