<template>
    <h3 class="text-center">Message Templates</h3>
    <ul>
        <div v-for="template in messageTemplatesIntermediate" :key="template.id" class="card bg-dark">
            <div class="card-header">{{ template.name }}</div>
            <div class="card-body">
                <FormatedText :value="template.message" :format="formatText" class="template-message"
                              @input="changeMessageTemplate(template.id, $event)"/>
                <br>
                <button class="btn btn-primary" @click="resetMessageTemplate(template.id)"
                        :disabled="messageTemplates.find(t => t.id === template.id).message === template.message">Reset
                </button>
                <button class="btn btn-success" @click="saveMessageTemplate(template.id)"
                        :disabled="messageTemplates.find(t => t.id === template.id).message === template.message">Save
                </button>
            </div>
        </div>
    </ul>
    <h3 class="text-center">Message Template Variables</h3>
    <p>
        <span v-for="(variable, key) in messageTemplateVariables" :key="key" class="badge badge-primary">
            {{ variable }}
        </span>
    </p>
    <hr>
    {{ messageTemplates }}
    <hr>
    {{ messageTemplatesIntermediate }}
</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},
    data() {
        return {
            messageTemplatesIntermediate: [],
        };
    },
    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.messageTemplatesIntermediate.forEach(template => {
                if (template.id === id) {
                    template.message = message;
                }
            });
        },
        saveMessageTemplate(id) {
            console.log(id);
        },
        resetMessageTemplate(id) {
            console.log(id);
        },
    },
    mounted() {
        this.fetchMessageTemplates().then(() => {
            this.messageTemplatesIntermediate = JSON.parse(JSON.stringify(this.messageTemplates));
        });
        this.fetchMessageTemplateVariables();
    },
};
</script>

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

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