<template>
    <v-app :theme="theme">
        <v-img
            v-bind:src="backgroundImage"
            width="100vw"
            height="100vh"
            cover
            class="bg-image"
        ></v-img>
        <v-app-bar app>
            <v-app-bar-title class="headline text-uppercase" v-if="smAndUp">
                <span v-if="appData.net !== '' && mdAndUp">{{ appData.net }}:</span>
                <span class="font-weight-light">{{ appData.name }}</span>
            </v-app-bar-title>

            <v-tabs
                v-model="activeTab"
                centered
            >
                <v-tab ripple to="/authors">{{ $t("authors") }}</v-tab>
                <v-tab ripple to="/books">{{ $t("books") }}</v-tab>
                <v-tab ripple to="/book">{{ $t("book") }}</v-tab>
            </v-tabs>

            <v-spacer></v-spacer>

            <v-btn
                :icon="theme == 'light' ? 'mdi-weather-night' : 'mdi-weather-sunny'"
                @click="toggleTheme"
            ></v-btn>
        </v-app-bar>

        <v-progress-linear
            indeterminate
            color="blue"
            v-if="showProgress"
        ></v-progress-linear>

        <v-main>
            <v-container fluid class="ma-0 pa-0">
                <transition name="fade">
                    <router-view
                        ref="view"
                        @authorSelected="loadBooks"
                        @bookSelected="loadBook"
                    />
                </transition>
            </v-container>
        </v-main>

        <v-footer app height="80" class="pa-0 ma-0">
            <v-card flat class="player-interface w-100" :class="{ 'solid-bg': smAndDown }">
                <v-list style="background: rgba(0,0,0,0)" color="rgba(0, 0, 0, 0)">
                    <v-list-item height="32" min-height="32" class="pb-0 pt-8">
                        <v-slider
                            v-model="progress"
                            min="0"
                            max="100"
                            dense
                            hide-details
                            :disabled="isOff"
                            :inverse-label="true"
                            :label="`${currentTime ? currentTime : '00:00:00'}/${duration ? duration : '00:00:00'}`"
                            class="time-slider w-100 px-2 py-0 m-0"
                        ></v-slider>
                    </v-list-item>
                    <v-list-item class="py-0">
                        <v-list-item-content v-if="smAndUp">
                            <v-list-item-title>{{ authorName }}</v-list-item-title>
                            <v-list-item-subtitle>{{ bookTitle }}<span v-if="currentChapter !== ''"> - {{ currentChapter }}</span></v-list-item-subtitle>
                        </v-list-item-content>

                        <v-spacer></v-spacer>

                        <v-list-item-action class="mx-2">
                            <v-btn
                                flat
                                icon="mdi-skip-backward"
                                @click="prevChapter"
                            >
                            </v-btn>
                        </v-list-item-action>

                        <v-list-item-action>
                            <v-btn
                                flat
                                icon
                                @click="toggleStatus"
                            >
                                <v-icon>mdi-{{ isPlaying ? "pause" : "play" }}</v-icon>
                            </v-btn>
                        </v-list-item-action>

                        <v-list-item-action class="mx-2">
                            <v-btn
                                flat
                                icon="mdi-skip-forward"
                                @click="nextChapter"
                            ></v-btn>
                        </v-list-item-action>

                        <v-card
                            flat
                            width="200"
                            height="35"
                            class="pr-6"
                        >
                            <v-slider
                                class="w-100"
                                :class="{ 'mr-3': mdAndUp, 'ml-3': mdAndDown }"
                                :min="0"
                                :max="10"
                                hide-details
                                v-model="volume"
                                prepend-icon="mdi-volume-low"
                                append-icon="mdi-volume-high"
                            ></v-slider>
                        </v-card>
                    </v-list-item>
                </v-list>
            </v-card>
        </v-footer>
        <!--
        <v-fab-transition>
            <v-btn
                class="to-top-button"
                v-show="scrolled"
                color="blue"
                @click="scrollToTop"
                dark
                fixed
                bottom
                right
                fab
            >
                <v-icon>keyboard_arrow_up</v-icon>
            </v-btn>
        </v-fab-transition>
        -->
        <message-box ref="MessageBox"/>
    </v-app>
</template>

<script>
    //import { ref, onMounted } from "vue";
    import { ref }        from "vue";
    import { useDisplay } from "vuetify";
    import MessageBox     from "./components/MessageBox";

    export default {
        name: "App",
        components: {
            MessageBox,
        },

        setup () {
            const theme = ref("light");
            const { smAndDown, smAndUp, mdAndUp, mdAndDown } = useDisplay();

            /*
            onMounted (() => {
                console.log("on mounted");
            })
            */

            return {
                theme,
                smAndDown,
                smAndUp,
                mdAndUp,
                mdAndDown,
                setTheme: (newTheme) => theme.value = newTheme === "light" || newTheme === "dark" ? newTheme : "light",
                toggleTheme: () => theme.value = theme.value === "light" ? "dark" : "light",
            }
        },

        data () {
            return {
                activeTab:       0,
                appData:         { name: "", net: "" },
                backgroundImage: this.defaultBackground,

                authors:        [],

                audioElement:   null,
                status:         0,
                currentChapter: null,
                volume:         5,

                scrolled:       false,
                useWikipedia:   true,
            }
        },

        watch: {
            "$route" (to) {
                if (to.path == "/authors") {
                    this.activeTab = this.tabs.authors;
                } else if (to.path == "/books") {
                    this.activeTab = this.tabs.books;
                } else if (to.path == "/book") {
                    this.activeTab = this.tabs.book;
                }
            },

            volume () { this.updateVolume(); }
        },

        computed: {
            isOff () {
                return this.audioElement == null;
            },

            isPaused () {
                return this.status === this.statuses.paused;
            },

            isPlaying () {
                return this.status === this.statuses.playing;
            },

            isChapterLoaded () {
                return (this.currentChapter !== null) && this.audioElement;
            },

            showProgress () {
                return false;
            }
        },

        mounted () {
            this.appData.name = this.$t("appName");
            this.appData.net  = this.appConfig.appNet;

            if (this.$router.currentRoute._value.path == "/authors") {
                this.activeTab = this.tabs.authors;
            } else if (this.$router.currentRoute._value.path == "/books") {
                this.activeTab = this.tabs.books;
            } else if (this.$router.currentRoute._value.path == "/book") {
                this.activeTab = this.tabs.book;
            }

            //window.addEventListener("scroll", this.onScroll);

            this.loadAuthors();
        },

        unmounted () {
            //window.removeEventListener("scroll", this.onScroll);
        },

        methods: {
            fillWikiInfo (searchText, fillAuthorInfo = true) {
                this.axios.get(`https://${this.$i18n.locale}.wikipedia.org/w/api.php`, {
                    params: {
                        format: "json",
                        action: "query",
                        prop: "extracts",
                        exintro: 1,
                        explaintext: 1,
                        redirects: 1,
                        titles: searchText,
                        origin: "*"
                    }
                }).then(response => {
                    if (Object.getOwnPropertyNames(response.data.query.pages)[0] > 0) {
                        let result = response.data.query.pages[
                            Object.getOwnPropertyNames(response.data.query.pages)[0]
                        ].extract;

                        if (fillAuthorInfo) {
                            let authorInfo  = this.$store.getters.author;
                            authorInfo.wiki = result;
                            this.$store.commit("setAuthor", authorInfo);
                        } else {
                            let bookInfo  = this.$store.getters.book;
                            bookInfo.wiki = result;
                            this.$store.commit("setBook", bookInfo);
                        }
                    } else {
                        if (fillAuthorInfo) {
                            let authorInfo  = this.$store.getters.author;
                            authorInfo.wiki = "";
                            this.$store.commit("setAuthor", authorInfo);
                        } else {
                            let bookInfo  = this.$store.getters.book;
                            bookInfo.wiki = "";
                            this.$store.commit("setBook", bookInfo);
                        }
                    }
                })
                .catch(error => {
                    this.isLoading = false;

                    if (fillAuthorInfo) {
                        let authorInfo  = this.$store.getters.author;
                        authorInfo.wiki = "";
                        this.$store.commit("setAuthor", authorInfo);
                    } else {
                        let bookInfo  = this.$store.getters.book;
                        bookInfo.wiki = "";
                        this.$store.commit("setBook", bookInfo);
                    }

                    console.error(error);
                });
            },

            getHash (val) {
                let CryptoJS = require("crypto-js");
                let hash     = CryptoJS.MD5(val);

                return hash.toString(CryptoJS.enc.Hex);
            },

            loadAuthors () {
                this.axios.get(`lib/authors.json?r=${Math.random()}`)
                    .then(response => {
                        this.$store.commit("setAuthors", response.data);
                        this.isLoading = false;
                    })
                    .catch(error => {
                        this.showMessage(this.$t("error"), error);
                        console.error(error);
                    })
            },

            /**
            * Load book data
            *
            * @param {object} bookData Book data
            */
            loadBook (bookData) {
                let author = this.$store.getters.author;

                this.$store.commit("setBook", {
                    author: author.name,
                    photo:  author.image,
                    title:  bookData.title,
                    cover:  bookData.image,
                    wiki:   ""
                });

                this.isLoading = true;

                this.axios.get(`${bookData.book}?r=${Math.random()}`)
                    .then(response => {
                        this.$store.commit("setChapters", response.data);

                        let bmKey    = this.getHash(JSON.stringify(this.$store.getters.chapters));
                        let bookmark = localStorage.getItem(bmKey) ? JSON.parse(localStorage.getItem(bmKey)) : null;

                        console.log(bmKey, bookmark);

                        if (this.useWikipedia) {
                            this.fillWikiInfo(bookData.title, false);
                        }

                        this.backgroundImage = bookData.image;
                        this.$router.push({ path: "/book" });
                        this.isLoading = false;
                    })
                    .catch(error => {
                        this.isLoading = false;
                        this.showMessage(this.$t("error"), error);

                        console.error(error);
                    });
            },

            /**
            * Load books data
            *
            * @param {object} authorData Author data
            */
            loadBooks (authorData) {
                this.isLoading = true;

                this.axios.get(`${authorData.books}?r=${Math.random()}`)
                    .then(response => {
                        let books = {};

                        response.data.forEach((book) => {
                            let cycle = book.cycle !== undefined ? book.cycle : "no_cycle";

                            if (books[cycle] == undefined) {
                                books[cycle] = [];
                            }

                            books[cycle].push(book);
                        });

                        this.$store.commit("setAuthor", {
                            name:  authorData.author || "",
                            image: authorData.image || "",
                            wiki:  ""
                        });

                        this.$store.commit("setBooks", books); // response.data);

                        if (this.useWikipedia) { this.fillWikiInfo(authorData.author); }

                        this.$router.push({ path: "/books" });

                        this.isLoading = false;
                    })
                    .catch(error => {
                        this.isLoading = false;
                        this.showMessage(this.$t("error"), error);

                        console.error(error);
                    })
            },

            onScroll () {
                this.scrolled = window.scrollY > 0;
            },

            showMessage (title, text) {
                this.$refs.MessageBox.title  = title;
                this.$refs.MessageBox.text   = text;
                this.$refs.MessageBox.dialog = true;
            },

            updateVolume () {
                this.audioElement ? this.audioElement.volume = (this.volume / 10) : null;
            }
        }
    }
</script>

<style lang="sass">
    .bg-image
        position: absolute
        filter: blur(10px) opacity(30%) !important
        img
            opacity: 100% !important

    .loading-progress
        margin: auto 15px

    .player-interface
        position: fixed !important
        bottom: 0
        .time-slider
            margin-top: -25px

    .to-top-button
        margin-bottom: 80px

    footer
        background: transparent !important

    .v-application.v-theme--
        &light
            header, footer > .v-card.player-interface
                background: rgba(255, 255, 255, .5)
            footer > .v-card.player-interface.solid-bg
                background: #fff
        &dark
            header, footer > .v-card.player-interface
                background: rgba(15, 15,15, .5)
            footer > .v-card.player-interface.solid-bg
                background: #000

    .content-container
        height: calc(100vh - 160px)
        overflow-y: auto
        overflow-x: hidden

    /* vuetify bugfix */
    .v-toolbar__content
        .v-tabs
            .v-btn
                height: inherit
</style>
