<script>
    import FormEdit from './FormEdit.vue';
    import FormCreate from './FormCreate.vue';

    const urlAPI = "http://localhost:7788/api/medals/";

    export default {
        components: {
            FormEdit, FormCreate
        },
        data() {
            return {
                tableData: []
            }
        },

        mounted() {
            this.loadData();
        },

        methods: {
            loadData() {
                fetch(urlAPI)
                    .then(response => response.json())
                    .then(data => this.updateTableData(data));
            },

            updateTableData(rawData) {
                this.tableData = this.processData(rawData);
            },

            processData(rawData) {
                return rawData.map(item => ({
                    ...item,
                    totalMedals: item.goldMedal + item.silverMedal + item.bronzeMedal
                }));
            },

            handleDelete(index, row) {
                console.log('To delete /medals/' + row.pk, index);
                fetch(urlAPI + row.pk, { method: 'DELETE' })
                    .then((response) => response.json())
                    .then((data) => {
                        const foundPos = this.tableData.findIndex(entry => entry.id == row.id);
                        if (foundPos >= 0) {
                            this.tableData.splice(foundPos, 1);
                        }
                    });
            },

            handleEdit(index, row) {
                console.log('To edit /medals/' + row.pk)
                this.$refs.formEdit.showDialog(row);
            },

            handleFormEditCancel() {
                console.log('handle form edit cancel');
            },

            handleFormEditConfirm(rec) {
                console.log('handle form edit confirm', rec);
                // to submit a fetch to update medals/rec.pk
                fetch(urlAPI + rec.pk, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(rec)
                })
                    .then((response) => response.json())
                    .then((data) => {
                        // update this.tableData
                        const foundPos = this.tableData.findIndex(entry => entry.pk == data.pk);
                        this.tableData[foundPos] = data;
                        this.updateTableData(data);
                    });
            },

            handleCreate() {
                //console.log('To edit /medals/'+row.pk)
                this.$refs.formCreate.showDialog();
            },

            handleFormCreateConfirm(rec) {
                console.log('handle form create confirm', rec);
                fetch(urlAPI, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(rec)
                })
                    .then((response) => response.json())
                    .then((data) => {
                        this.updateTableData(data)
                        // Push the new item with totalMedals calculated
                        this.tableData.push(newItem);
                    });
            }
        }
    }
</script>

<template>

    <el-table :data="tableData" style="width: 80%">
        <el-table-column prop="nationality" label="Nationality" width="300" sortable />
        <el-table-column prop="name" label="Name" width="140" sortable />
        <el-table-column prop="goldMedal" label="Gold Medal" width="160" sortable />
        <el-table-column prop="silverMedal" label="Silver Medal" width="160" sortable />
        <el-table-column prop="bronzeMedal" label="Bronze Medal" width="160" sortable />
        <el-table-column prop="totalMedals" label="Total Medals" width="160" sortable />
        <el-table-column label="Operations">
            <template #default="scope">
                <el-button type="primary" size="mini" plain @click="handleEdit(scope.$index, scope.row)">Edit</el-button>
                <el-button type="danger" size="mini" plain @click="handleDelete(scope.$index, scope.row)">Delete</el-button>
            </template>
        </el-table-column>

    </el-table>

    <el-button @click="handleCreate">Add new medals</el-button>

    <form-edit ref="formEdit" @cancel="handleFormEditCancel" @confirm="handleFormEditConfirm">
    </form-edit>

    <!-- @cancel is ignored  -->
    <form-create ref="formCreate" @confirm="handleFormCreateConfirm">
    </form-create>

</template>

<style scoped>
</style>

why it won't auto loadData() when create? and why updateTableData(rawData) is not working when i update?