import {createApp} from 'vue';
import listitem from '../vue/ListItem.vue';


const lists = document.querySelectorAll('.webien-reactive-list-app');


lists.forEach((list) => {

    let app = createApp({
        name: 'List-' + list.dataset.unique,
        data() {
            return {
                appSettings: window['app_' + list.dataset.unique],
                appPosts: window['posts_' + list.dataset.unique],
                appTerms: window['terms_' + list.dataset.unique],
                postsHasFilter: false,
                activeTerm: false,
                postsSearchTerm: '',
                scene: {
                    view: 'list'
                },
                appReady: false
            }
        },
        mixins: [

        ],
        computed: {
            posts() {
                if (typeof this.appPosts !== 'undefined') {
                    return this.appPosts; // From array defined in DOM
                } else {
                    return [];
                }
            },
            terms() {
                if (typeof this.appTerms !== 'undefined') {
                    return this.appTerms; // From array defined in DOM
                } else {
                    return [];
                }
            },

            postsFiltered() {
                if(this.activeTerm && this.postsSearchTerm === ''){
                    return this.filterByTerm(this.activeTerm);
                }

                return this.searchPosts(this.postsSearchTerm)
            },
            noMatches() {
                for (const item in this.postsFiltered) {
                    if(this.postsFiltered[item].length){
                        return false;
                    }
                }
                return true;
            }
        },
        watch: {
            postsSearchTerm(newSearch, oldSearch) {
                if (newSearch.length > 0) {
                    this.postsHasFilter = true;
                } else {
                    this.postsHasFilter = false;
                }
            },
        },
        methods: {

            searchPosts(str) {
                let arr = {};

                // If search is empty and having most popular, add it to the first in list
                if(str === '' && this.posts['most_popular']){
                    arr[this.mostPopularTitle] = this.posts['most_popular'];
                    // remove most popular from list
                }

                // Loop object and return matches
                for (const item in this.posts) {
                    arr[item] = this.posts[item].filter(
                        (x) =>
                            x.title && x.title.toLowerCase().includes(str.toLowerCase()) && x.termName !== 'most_popular'
                    );
                }

                // Remove most popular original data from list
                delete arr['most_popular'];

                return arr;
            },
            closePost(item){
                this.resetList();
            },
            headingId(txt) {
                return txt.replace(/[^a-zA-Z0-9]/g, '-').toLowerCase();
            },
            listItemClicked(item){
                let app = this;

                if(!item.open) {
                    this.resetList();
                }

                // Check what to do, depending on context
                if(this.appSettings.behavior === 'expand') {
                    // toggle open value
                    item.open = !item.open;

                    // Update url
                    this.updateUrl(item.id);


                    // Check what context we are in
                    let $el = jQuery('.full_list .list-items li.item-' + item.id);

                    if($el.length){
                        this.$nextTick(() => {
                            // Scroll into view
                            if(app.appSettings.scroll) {
                                jQuery([document.documentElement, document.body]).animate({
                                    scrollTop: $el.offset().top - 100
                                }, 400);
                            }
                        });
                    }
                }
                else if(this.appSettings.behavior === 'link') {
                    if(item.link){
                        window.location.href = item.link;
                    }
                }
                else if(this.appSettings.behavior === 'download') {
                    if(item.link){
                        console.log('download', item.link);
                    }
                }

/*
                let shouldOpen = !item.open && !item.link && this.appSettings.behaviour === 'expand';



                if(!shouldOpen){
                    this.updateUrl(null);
                    return;
                }
*/



            },
            filterByTerm() {
                let vm = this;
                this.activeTermTypes = [];

                let arr = {};
                // Loop object and return matches
                for (const item in this.posts) {
                    arr[item] = this.posts[item].filter(function(x) {

                        if(x.terms[0].term_id === vm.activeTerm){
                            return true;
                        }

                    });
                }

                return arr;

            },
            resetList() {

                for (let arr in this.posts) {
                    this.posts[arr].forEach(function(listItem){
                        listItem.open = false;
                    });
                }

            },

            updateUrl(hash) {

                if(hash){
                    history.pushState({}, "", "#" + hash);
                } else {
                    history.pushState({}, "", "");
                }
            }


        },
        mounted: function () {

            this.appReady = true;

            // Check for url item
            window.addEventListener("load", (event) => {
                if(window.location.hash) {
                    let hash = window.location.hash.substring(1);
                    let item = document.querySelector('.item-' + hash + ' .head');

                    // If expand is allowed, click it
                    if(this.appSettings.behaviour === 'expand') {
                        item.click();
                    }

                }
            });


        },
        created() {


        },
        components: {
            listitem,
        },
    });


    // Mount app to DOM
    if(document.getElementById('list-' + list.dataset.unique)){
        app.mount('#list-' + list.dataset.unique);
    }


});



