const app = new Vue({
    el: '#adminedit',
    template: `
<div>
<div id="msg" v-if="error !== ''"> {{ error }}</div>
<table class="ui celled striped inverted table">
    <thead>
    <tr>
        <th>Name</th>
        <td v-if="mode === 0">Gemeinde</td>
        <th>KonfiCoins</th>
        <th v-if="mode === 1">Konfis</th>
        <th v-if="mode === 1">Konficoins pro Person</th>
        <th>Bearbeiten</th>
    </tr>
    </thead>
    <tbody id="list">
    <tr v-if="data.length === 0">
        <td colspan="5">Laden...</td>
    </tr>
    <tr v-for="(item, i) in data" :class="{ active: currentRow === item.id }">
        <td>{{ item.name }}</td>
        <td v-if="mode === 0">{{ item.gemeinde }}</td>
        <td>{{ item.kcoins.toLocaleString('de-DE') }}</td>
        <td v-if="mode === 1">{{ item.konfi_count }}</td>
        <td v-if="mode === 1">{{ parseFloat((item.coins_quota).toFixed(2)).toLocaleString('de-DE') }}</td>
        <td>
            <span class="ui action input">
                <input type="number" :tabindex="(i +1)" @focus="currentRow = item.id" @keyup.enter="updateCoins(item.id)" autocomplete="off" v-model="formStuff[item.id].addCoins"/>
                <a class="ui right labeled icon button green" @click="updateCoins(item.id)">
                    <i class="right dollar icon"></i>
                    KonfiCoins Hinzufügen
                </a>
            </span>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <a v-if="!formStuff[item.id].showDelete" class="ui button red" @click="formStuff[item.id].showDelete = true">
                Löschen
            </a>
            <span v-if="formStuff[item.id].showDelete">
                Sicher?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <a class="ui button red" @click="deleteStuff(item.id)">
                    Löschen
                </a>
                <a class="ui button" @click="formStuff[item.id].showDelete = false">
                    Abbrechen
                </a>
            </span>
        </td>
    </tr>
    </tbody>
</table>
</div>`,
    data() {
        return {
            mode: 1,
            data: [],
            error: '',
            addCoins: 0,
            loading: false,
            formStuff: {},
            currentRow: 0,
        }
    },
    beforeMount() {
        this.mode = mode
    },
    mounted() {
        if (typeof (EventSource) === "undefined") {
            this.error = 'Diese Browser wird nicht unterstützt.'
            return
        }

        let source = new EventSource('/events');
        source.onmessage = e => {
            console.debug('unsupported event!', e)
        };
        source.addEventListener('init', e => {
            this.data = JSON.parse(e.data)
            for (const i in this.data) {
                this.$set(this.formStuff, this.data[i].id, {addCoins: 0, showDelete: false})
            }
            this.sortData()
        })
        source.addEventListener('update', e => {
            this.update(JSON.parse(e.data))
        })
        source.addEventListener('create', e => {
            this.create(JSON.parse(e.data))
        })
        source.addEventListener('delete', e => {
            this.delete(JSON.parse(e.data))
        })
    },
    methods: {
        sortData() {
            this.data.sort((a, b) => {
                return a.name < b.name ? -1 : 1
            })
        },
        update(updatedData) {
            for (const i in this.data) {
                if (this.data[i].id === updatedData.id) {
                    this.$set(this.data, i, updatedData)
                }
            }
            this.sortData()
        },
        create(createdData) {
            this.data.push(createdData)
            this.$set(this.formStuff, createdData.id, {addCoins: 0, showDelete: false})
            this.sortData()
        },
        delete(deletedData) {
            for (const i in this.data) {
                if (this.data[i].id === deletedData.id) {
                    this.data.splice(i, 1)
                }
            }
            this.sortData()
        },
        updateCoins(id) {
            this.loading = true

            if (this.formStuff[id].addCoins == 0) {
                return
            }

            let formData = new FormData();
            formData.append('id', id);
            formData.append('addcoins', this.formStuff[id].addCoins);

            fetch('/admin/update', {
                method: 'POST',
                body: formData
            })
                .catch(e => {
                    this.error = e
                })
                .finally(() => {
                    this.loading = false
                    this.$set(this.formStuff, id, {addCoins: 0, showDelete: false})
                })
        },
        deleteStuff(id) {
            this.loading = true
            let formData = new FormData();
            formData.append('id', id);

            fetch('/admin/delete', {
                method: 'POST',
                body: formData
            })
                .catch(e => {
                    this.error = e
                })
                .finally(() => {
                    this.loading = false
                })
        },
    },
});

// Konfi hinzufügen
$('.ui.kofiadd.modal')
    .modal({
        duration: 200,
        onApprove : function() {
            $('.loader').addClass('active');
            $.ajax({
                url: '/admin/add',
                method: 'POST',
                data: 'name=' + $('#name').val() + '&gemeinde=' + $('#gemeinde').val(),
                success: function (msg) {
                    $('.loader').removeClass('active');

                    if (msg === 'success') {
                        $('#name').val('');
                        $('#gemeinde').val('');

                        getList();
                        $('#msg').html('<div class="ui success message" style="display: block;">Der Konfi wurde erfolgreich hinzugefügt.</div>');
                    } else {
                        $('#msg').html('<div class="ui error message" style="display: block;">Ein Fehler trat auf.</div>');
                    }
                }
            });
        }
    })
    .modal('attach events', '.addKofi.button', 'show')
;

$('.ui.gemeindeadd.modal')
    .modal({
        duration: 200,
        onApprove : function() {
            $('.loader').addClass('active');
            $.ajax({
                url: '/admin/add',
                method: 'POST',
                data: 'name=' + $('#name').val() + '&konfis=' + $('#konfis').val(),
                success: function (msg) {
                    $('.loader').removeClass('active');
                    if (msg === 'success') {
                        $('#name').val('');
                        $('#msg').html('<div class="ui success message" style="display: block;">Die Gemeinde wurde erfolgreich hinzugefügt.</div>');
                    } else {
                        $('#msg').html('<div class="ui error message" style="display: block;">Ein Fehler trat auf.</div>');
                    }
                }
            });
        }
    })
    .modal('attach events', '.addGemeinde.button', 'show')
;

$('.ui.kofiupload.modal')
    .modal('attach events', '.ui.right.labeled.icon.uploadKofis.button.blue', 'show')
;