<template>
    <container>
        <div class="blog-links">
            <a href="javascript:void(0)" @click="$router.push({ name: 'blog' })"><i class="fas fa-backward"></i> Back</a>
            <router-link :to="{ name: 'blog-article-edit', params: { id } }" v-if="admin"><i class="fas fa-edit"></i> Edit</router-link>
        </div>
        <div class="article" v-if="!loading && !error">
            <h1>{{ title }}</h1>
            <div class="content" v-html="content"></div>
        </div>
        <div v-else-if="!!error && errorCode === 404">
            <p>Not found</p>
        </div>
        <div v-else-if="!!error">
            <p>{{ error }}</p>
        </div>
    </container>
</template>

<script>
import Container from "../components/Container.vue";
import NotFound from "./NotFound";

export default {
    components: {
        NotFound,
        Container,
    },
    data() {
        return {
            loading: false,
            errorCode: null,
            error: null,
            title: null,
            date: null,
            summary: null,
            content: null,
        };
    },
    props: {
        id: String|Number,
        slug: String,
        admin: false,
    },
    mounted() {
        console.error("asdf");
        axios.get(`/api/blog/${this.id}`)
            .then(res => {
                if (res.status > 399) {
                    this.errorCode = res.status;
                    this.error = res.statusText;
                    return;
                }

                this.title = res.data.title;
                this.date = moment(res.data.date);
                this.summary = res.data.summary;

                const converter = new showdown.Converter({
                    tables: true,
                });
                this.content = converter.makeHtml(res.data.content);

                this.loading = false;
            }).catch(error => {
                this.errorCode = error.response.status;
                this.error = error.message;
            });
    },
}
</script>
