<template>
    <container>
        <p>
            <span v-if="!!tokenId">Authenticated with token ID {{ tokenId }}</span>
            <br/>
            Authentication status: {{ status ? 'Valid' : 'Invalid' }}
            <button @click="checkValidity">Refresh</button>
            <br/>
            <button @click="logout">Logout</button>
        </p>
    </container>
</template>

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

export default {
    components: {
        Container,
    },
    data() {
        return {
            status: false,
            tokenId: null
        };
    },
    mounted() {
        if (!this.getCurrentToken()) {
            this.requestNewToken();
        } else {
            this.checkValidity();
        }
    },
    methods: {
        requestNewToken() {
            axios.post('/api/auth')
                .then(res => {
                    window.localStorage.setItem('authentication-token', JSON.stringify(res.data));
                    axios.defaults.headers.common.Authorization = res.data.token;
                    this.tokenId = res.data.id;
                });
        },
        checkValidity() {
            axios.get('/api/auth')
                .then(res => {
                    this.status = res.data.status;
                });
        },
        getCurrentToken() {
            const tokenData = JSON.parse(window.localStorage.getItem('authentication-token'));

            if (!!tokenData) {
                if (new Date(tokenData.valid_until) > new Date()) {
                    this.tokenId = tokenData.id;
                    axios.defaults.headers.common.Authorization = tokenData.token;
                    return tokenData.token;
                }
            }
        },
        logout() {
            axios.defaults.headers.common.Authorization = null;

            if (!!window.localStorage.getItem('authentication-token')) {
                window.localStorage.removeItem('authentication-token');
            }

            this.status = false;
            this.tokenId = null;
        },
    }
}
</script>
