<template>
    <v-card>
        <v-toolbar flat color="secondary" class="mt-12" dark>
            <v-toolbar-title>Create a note</v-toolbar-title>
        </v-toolbar>

        <v-alert v-if="conflict" type="error">
            A note with the same title already exists
        </v-alert>

        <v-form ref="form" lazy-validation>
            <v-card-text>
                <v-text-field
                    v-model="form.title"
                    label="Title"
                    outlined
                    value="My new note"
                ></v-text-field>

                <v-combobox
                    v-model="form.tags"
                    outlined
                    :items="possibleTags"
                    :delimiters="delimiters"
                    label="Tags"
                    multiple
                    chips
                    deletable-chips
                ></v-combobox>
            </v-card-text>

            <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn color="success" depressed @click="createNote">
                    Create
                </v-btn>
            </v-card-actions>
        </v-form>
    </v-card>
</template>

<script>
export default {
    name: 'Create',
    data: () => ({
        delimiters: [' ', ','],
        form: {
            title: '',
            tags: [],
        },
        possibleTags: [],
        conflict: false,
    }),
    mounted() {
        this.$axios
            .get('/tags')
            .then((e) => (this.possibleTags = e.data))
            .catch((e) => {
                console.log(e)
            })
    },
    methods: {
        createNote() {
            this.conflict = false
            this.$axios
                .post(`/notes/${this.form.title}`, {
                    tags: this.form.tags,
                })
                .then((_) => {
                    this.$router.push('/notes')
                })
                .catch((e) => {
                    if (e.response && e.response.status === 409) {
                        this.conflict = true
                    } else {
                        console.log('??')
                    }
                })
        },
    },
}
</script>

<style scoped></style>
