<template>
    <div class="p-4">
        <div class="flex justify-between flex-center mb-4">
            <a href="#" class="btn" @click="$router.back()">Back</a>
            <router-link :to="'/memos/create'" class="btn-primary">Add New Memo</router-link>
        </div>
        <Loader v-if="loading" />
        <div v-else class="flex flex-wrap -m-2">
            <div v-if="memos.lenght === 0">
                <p>No memos yet. <router-link to="/memos/create">Get Started ></router-link></p>
            </div>
            <router-link v-for="memo in memos" :key="memo.data.memo_id" :to="'/memos/' + memo.data.memo_id" class="w-full sm:w-1/2 md:w-1/3 lg:w-1/4">
                <div class="m-2 max-w-lg rounded overflow-hidden shadow-lg bg-white">
                    <img :src="memo.data.attributes.thumbnail_cover_image.data.attributes.path" alt="" class="w-full">
                    <div class="px-6 py-4">
                        <h1 class="text-gray-700">{{ memo.data.name }}</h1>
                    </div>
                    <div class="flex justify-end py-2">
                        <span class="inline-block bg-gray-400 text-white rounded-full px-3 py-1 text-sm font-semibold mr-2">{{ memo.data.last_updated }}</span>
                    </div>
                </div>
            </router-link>
        </div>
    </div>
</template>

<script>
import Loader from '../../components/Loader'

export default {
    name: 'MemoIndex',
    components: {
        Loader
    },
    data: function () {
        return {
            loading: true,
            memos: null,
        }
    },
    mounted() {
        // eslint-disable-next-line no-undef
        axios.get('/api/memos')
            .then(response => {
                this.memos = response.data.data
                this.reorderList()
                this.loading = false
            })
            .catch(() => {
                this.loading = false
                console.log('Unable to fetch memos.')
            })
    },
    methods: {
        reorderList() {
            this.memos.sort(function(a, b) {
                return a.data.last_updated_timestamp + b.data.last_updated_timestamp
            })
        }
    }
}
</script>
