<!-- components/Login.vue -->
<template>
    <div>
        <div v-if="!authenticated">
            <section class="hero is-primary">
                <div class="hero-body">
                    <div class="container">
                        <div class="has-text-centered">
                            <h2 class="title">Login or Register</h2>
                            <p class="subtitle error-msg">{{ errorMsg }}</p>

                        </div>

                        <!--
                        <ul>
                            <li v-for="(provider, index) in loginProviders" v-bind:id="index">
                                <a :href="provider.url">{{ index }} ({{provider.type}})</a>
                            </li>
                        </ul>
                        -->
                        <b-tabs>
                            <b-tab title="KIT Login" active>
                                <p>{{$t('Use your KIT account to connect to LRC. If this is your first login to LRC this creates a new account')}}!</p>

                                <div v-if="!this.$isProduction" style="background-color: lightcoral; padding: 10px; margin: 10px;">
                                    <h4>DEBUG DEBUG</h4>
                                    <button v-on:click="oidc_login">Login via OIDC (function)</button><br/>
                                    <a class="btn btn-info" role="button"
                                       href="//localhost:5443/api/auth/oidc?redirect_url=/login">OIDC with redirect (localhost)</a><br/>
                                    <a href="https://ubkaps154.ubka.uni-karlsruhe.de:5443/api/auth/oidc?redirect_url=/login">OIDC with redirect (ubkaps154.ubka.uni-karlsruhe.de)</a><br/>
                                    <br/>
                                </div>
                                <a class="btn btn-primary" role="button" href="/api/auth/oidc?redirect_url=/login">{{$t('Login with KIT account')}}</a>
                            </b-tab>
                            <b-tab title="Alternative Login">
                                <div class="field">
                                    <label class="label  is-large" for="email">Email:</label>
                                    <div class="control">
                                        <input type="email" class="input is-large" id="email" v-model="email">
                                    </div>
                                </div>
                                <div class="field">
                                    <label class="label  is-large" for="password">Password:</label>
                                    <div class="control">
                                        <input type="password" class="input is-large" id="password" v-model="password">
                                    </div>
                                </div>

                                <div class="control">
                                    <a class="btn btn-primary is-large is-primary" @click="authenticate">Login</a>
                                </div>
                            </b-tab>
                            <b-tab :title="$t('Register')" v-bind:disabled="this.$isProduction">
                                <form
                                @submit="checkLoginForm">
                                <div class="field">
                                    <label class="label  is-large" for="email">Email:</label>
                                    <div class="control">
                                        <input type="email" class="input is-large" id="regEmail" v-model="regEmail">
                                    </div>
                                </div>
                                <div class="field">
                                    <label class="label  is-large" for="password">Password:</label>
                                    <div class="control">
                                        <input type="password" class="input is-large" id="regPassword" v-model="regPassword">
                                    </div>
                                </div>

                                <div class="control">
                                    <a class="btn btn-primary is-large is-success" @click="register">{{$t('Register')}}</a>
                                </div>
                                </form>
                            </b-tab>
                        </b-tabs>
                    </div>
                </div>
            </section>
        </div>
        <div v-else>
            <h1>{{ $t('You are already logged in!') }}</h1>
            <h2>{{$t('Redirecting you to')}}
                <router-link :to="{name: redirectTarget}">{{redirectTarget}}</router-link>
                {{$t('in')}} {{redirectTime}} {{$t('seconds')}}.
            </h2>
            <p><a href="" @click.prevent="logout()">{{$t('logout')}}</a></p>
        </div>
    </div>
</template>

<script>
    import {EventBus} from '@/utils';

    export default {

        data() {
            return {
                email: '',
                password: '',
                regEmail: '',
                regPassword: '',
                errorMsg: '',
                redirectMsg: '',
                redirectTarget: 'profile',
                redirectTime: 5,
                loginProviders: [],
                redirect_interval: null,
            };
        },
        methods: {
            authenticate() {
                this.$store.dispatch('login', {email: this.email, password: this.password})
                    .then(() => this.$router.push('/'));
            },
            register() {
                this.$store.dispatch('register', {email: this.regEmail, password: this.regPassword})
                    .then(() => this.$router.push('/'));
            },
            oidc_login() {
                this.$store.dispatch('oidc_login', '\\oidc_login_redirection');
            },
            logout() {
                this.$store.dispatch('logout', {revokeRefreshToken: true});
                this.$router.push({name: 'home'});
            },
            checkLoginForm(e) {
                if (this.email && this.password){
                    return true;
                }
                this.errors = [];

                if (!this.email){
                    this.errors.push('E-Mail required')
                }

                if (!this.password){
                    this.errors.push('Password required')
                }

                e.preventDefault();
            }
        },
        mounted() {
            // this.$parent.$data.isLoading = true;
            EventBus.$on('failedRegistering', (msg) => {
                this.errorMsg = msg;
            });
            EventBus.$on('failedAuthentication', (msg) => {
                this.errorMsg = msg;
            });
            EventBus.$on('loginProvidersLoaded', (providers) => {
                this.loginProviders = providers;
            });
            EventBus.$on('storedTokens', () => {
                this.$store.dispatch('loadUsers');
                this.$store.dispatch('loadProfile');
            });

            this.$store.dispatch('loadLoginProviders');

            // get tokens
            if (this.$cookies.isKey('tokens')) {
                this.$store.dispatch('storeTokens', JSON.parse(atob(this.$cookies.get('tokens'))));
                this.$cookies.remove('tokens');
            }

            this.$nextTick(() => {
                if (this.authenticated) {
                    if (this.$route.query.redirectionTarget) {
                        this.redirectTarget = this.$route.query.redirectionTarget;
                    }
                    this.redirect_interval = window.setInterval(() => {
                        this.redirectTime = this.redirectTime - 1;
                        if (this.redirectTime < 0) {
                            clearInterval(this.redirect_interval);
                            this.$router.push({name: this.redirectTarget});
                        }
                    }, 1000);
                }
            });
        },
        beforeDestroy() {
            clearInterval(this.redirect_interval);
            EventBus.$off('failedRegistering');
            EventBus.$off('failedAuthentication');
        },
        computed: {
            users() {
                return this.$store.state.users;
            },
            authenticated() {
                return this.$store.getters.isAuthenticated;
            },
        },
    };
</script>

<style lang="scss">
    .error-msg {
        color: red;
        font-weight: bold;
    }
</style>
