<script>
    import axios from 'axios'
    import Config from '@/config.js'
    import { useQuestionStore } from '@/stores/questions.js'
    import { useAnswersStore } from '@/stores/answers.js'
    import { useResultsStore } from '@/stores/results.js'

    export default {
        setup() {
            const questionStore = useQuestionStore()
            const answersStore = useAnswersStore()
            const resultsStore = useResultsStore()

            return {
                questionStore,
                answersStore,
                resultsStore
            }
        },
        name: 'QuestionIndex',
        created() {
            if (this.questionStore.questions.length == 0) {
                this.getQuestions()
            }
        },
        mounted() {
            if (this.answersStore.quizCurrent !== null) {
                this.$router.push(`/quiz/question/${this.answersStore.quizCurrent}`)
            } else {
                this.answersStore.$reset()
            }
            this.resultsStore.$reset()
        },
        methods: {
            getQuestions() {
                axios.get(`${Config.SERVER}api/questions/`)
                    .then((response) => {
                        console.log('Fetched questions from server.')
                        this.questionStore.storeQuestions(response.data)
                    })
                    .catch( error => {
                        console.log(error)
                        this.$router.push('/err_refused')
                    })
            }
        }
    }
</script>
<template>
    <div>
        <router-view v-slot="{ Component, route }" class="w-full" ref="panel" appear>
            <Transition mode="out-in"
                enter-active-class="transition-all duration-300 origin-center ease-in"
                enter-from-class="transform opacity-0 md:scale-95"
                leave-active-class="transition-all duration-300 origin-center ease-out"
                leave-to-class="transform opacity-0 md:scale-95"
            >
                <component :is="Component" :key="route.path"/>
            </Transition>
        </router-view>
    </div>
</template>