<template>
    <div class="home">
        <div class="container">
            <section class="section">
                <HelloWorld v-if="!authenticated" msg="you are not authenticated!"/>
                <div v-else>
                    <h1>Welcome <span v-if="profile.last_seen!=null">back</span> {{$store.getters.getUserName}}! <span
                            v-if="profile.last_seen!=null">(Last seen: {{profile.last_seen | moment("dddd, MMMM Do YYYY")}})</span>
                    </h1>

                    <ErroneousRecorders/>

                    <p>{{$t('Add favorite recorder:')}}</p>
                    <SelectRecorder @recorderSelected="addFavoriteRecorderToProfile"/>

                    <div v-if="profile.favorite_recorders.length >0">
                        <hr/>
                        <p>{{$t('Favorite recorders:')}}</p>
                        <b-card-group deck>
                            <RecorderState v-for="recorder in profile.favorite_recorders" :recorder="recorder" v-bind:key="recorder.id"/>
                        </b-card-group>
                    </div>
                </div>
            </section>
        </div>

        <router-link :to="{name: 'recorder', params: {recorder_id: 1}}">rec 1</router-link>
    </div>
</template>

<script>
    import {Component, Vue} from 'vue-property-decorator';
    import HelloWorld from '@/components/HelloWorld.vue'; // @ is an alias to /src
    import i18n from '@/plugins/i18n';
    import ErroneousRecorders from '@/components/ErroneousRecorders.vue';
    import SelectRecorder from '@/components/SelectRecorder.vue';
    import RecorderState from '@/components/RecorderState.vue';
    import getRepository from '@/api/RepositoryFactory';

    const userRepository = getRepository('user');

    @Component({
        components: {
            ErroneousRecorders,
            RecorderState,
            SelectRecorder,
            HelloWorld,
        },
    })
    export default class Home extends Vue {
        data() {
            return {};
        }

        mounted() {
            if (this.authenticated) {
                if (this.profile == null || Object.keys(this.profile).length === 0) {
                    this.$parent.$data.isLoading = true;
                    this.$store.dispatch('loadProfile').then(() => {
                        this.$parent.$data.isLoading = false;
                    });
                }
            }
        }

        addFavoriteRecorderToProfile(recorder) {
            userRepository.addFavoriteRecorder(recorder.recorder_id).then(() => {
                this.$store.dispatch('loadProfile');
            });
        }

        get authenticated() {
            return this.$store.getters.isAuthenticated;
        }

        get profile() {
            return this.$store.state.profile;
        }

    }
</script>

<style>

</style>
