<template>
    <div class="p-2">
        <div class="flex-between">
            <a href="#" @click="$router.back()" class="link">
                < Back
            </a>
        </div>
        <form @submit.prevent="submitForm">
            <InputField name="name" :data="form.name" label="Memo Title" placeholder="Your Title" @update:field="form.name = $event" :errors="errors" />
            <TextAreaField name="memo" :data="form.memo" label="Memo" placeholder="Your Memo" @update:field="form.memo = $event" :errors="errors" />

            <div class="flex-end">
                <button class="btn-alert mr-3">Cancel</button>
                <button class="btn-primary">Save</button>
            </div>

        </form>
    </div>
</template>

<script>
    import InputField from "../../components/InputField";
    import TextAreaField from "../../components/TextAreaField";

    export default {
        name: "MemoEdit",
        components: {
            InputField, TextAreaField
        },
        data: function () {
            return {
                form: {
                    'name': '',
                    'memo': '',
                },
                errors: null,
                loading: true,
            }
        },
        methods: {
            submitForm: function () {
                axios.patch('/api/memos/' + this.$route.params.id, this.form)
                    .then(response => {
                        this.$router.push(response.data.links.self)
                    })
                    .catch(errors => {
                        this.errors = errors.response.data.errors
                    })
            }
        },
        mounted() {
            axios.get('/api/memos/' + this.$route.params.id)
                .then(response => {
                    this.form = response.data.data
                    this.loading = false
                })
                .catch(error => {
                    this.loading = false
                    if (error.response.status === 404) {
                        this.$router.back()
                    }
                })
        }
    }
</script>
