import Vue from 'vue/dist/vue'
import BuilderClient from "../api/BuilderClient";

Vue.component('brick-template', {
    delimiters: ['<<', '>>'],
    props: [
        'builder',
        'selectTemplate',
        'deleteTemplate',
    ],
    data: function () {
        return {
            templates: [],
            isLoading: false,
        };
    },
    methods: {
        getTemplates() {
            this.beginLoading();
            BuilderClient
                .get('/template')
                .then((json) => {
                    this.templates = json;
                    this.finishLoading();
                });
        },
        getTemplateDate(template) {
            if (template.templatedAt) {
                return new Date(template.templatedAt).toLocaleDateString('fr-FR');
            }
        },
        _selectTemplate(id) {
            this.selectTemplate(id);
        },
        _deleteTemplate(id) {
            this.deleteTemplate(id);
        },
        beginLoading: function () {
            this.isLoading = true;
        },
        finishLoading: function () {
            this.isLoading = false;
        },
    },
    mounted() {
        this.getTemplates();
    },
    template: `
      <div class="brick-templates">
        <div v-if="this.isLoading" v-html="this.builder.context.loader" ></div>
        <button
          v-if="!this.isLoading"
          v-for="template in templates"
          class="brick-template btn"
          v-on:click="_selectTemplate(template.id)"
          :title="template.templateName"
        >
          <img :src="template.icon" :alt="template.templateName" height="60"/>
          <span><< template.templateName >></span>
          <small v-html="getTemplateDate(template)"></small>
          <button
            class="brick-template-delete btn"
            v-on:click.stop="_deleteTemplate(template.id)"
          >
            <i class="fas fa-times"></i>
          </button>
        </button>
      </div>
    `,
});