import {yasrDrawRankings} from "../../../includes/js/src/ranking";
const  { __ } = wp.i18n; // Import __() from wp.i18n

let activeTab;
let tabClass = document.getElementsByClassName('nav-tab-active');

if(tabClass.length > 0){
    activeTab = document.getElementsByClassName('nav-tab-active')[0].id;
}

if (activeTab === 'rankings') {

    let elementsClassParents = '.yasr-builder-elements-parents'; //class shared between all elements
    let elementsClassChilds  = '.yasr-builder-elements-childs'; //class shared between all elements

    jQuery(elementsClassParents).prop('disabled', true);   //disable all parents elements;
    jQuery(elementsClassChilds).prop('disabled', true);    //disable all childs elements;

    //add action in yasr-settings-page
    wp.hooks.doAction('yasrBuilderBegin', elementsClassParents, elementsClassChilds);

    let shortcode;
    let filterShortcodeAttributes = [];

    //initialize shortcode attributes
    let shortcodeAttributes = yasrReturnShortcodeAttributes();

    shortcode = shortcodeAttributes['name'];
    document.getElementById('yasr-builder-shortcode').textContent = '['+shortcode+']';
    document.getElementById('yasr-builder-copy-shortcode').setAttribute('data-shortcode', '['+shortcode+']');

    const previewButton    = document.getElementById('yasr-builder-button-preview');
    const copyButton       = document.getElementById('yasr-builder-copy-shortcode');
    const previewDiv       = document.getElementById('yasr-builder-preview');

    //This is the select for data Source
    const selectDataSource = document.getElementById('yasr-ranking-source');
    const divView          = document.getElementById('builder-vv-default-view');
    const divVotes         = document.getElementById('builder-vv-required-votes');
    const divSize          = document.getElementById('builder-stars-size');
    const divOverallTxt    = document.getElementById('builder-overall-text');
    const divUsername      = document.getElementById('builder-username-options');
    const divCategory      = document.getElementById('builder-category');
    const divCpt           = document.getElementById('builder-cpt');

    let dataSource     = selectDataSource.value;
    let previewClicked = false;

    //if on page load is overall_rating (e.g. on page refresh) text div must be displayed
    if(dataSource === 'yasr_ov_ranking') {
        yasrBuilderOvOptions(divOverallTxt, divSize, divView, divVotes, divUsername, divCategory, divCpt);
    }
    else if(selectDataSource.value === 'yasr_most_active_users' || selectDataSource.value === 'yasr_top_reviewers') {
        yasrBuilderNoStarsOptions (divOverallTxt, divSize, divView, divVotes, divUsername, divCategory, divCpt);
    }

    //event listener for all change events
    document.addEventListener('change', event => {
        if(event.target.id === 'yasr-ranking-source') {
            //when event is on main select, be sure the preview div is empty

            previewDiv.innerHTML = '';
            if(event.target.value === 'yasr_ov_ranking') {
                yasrBuilderOvOptions (divOverallTxt, divSize, divView, divVotes, divUsername, divCategory, divCpt);
            }
            else if(event.target.value === 'yasr_most_active_users' || event.target.value === 'yasr_top_reviewers') {
                yasrBuilderNoStarsOptions (divOverallTxt, divSize, divView, divVotes, divUsername, divCategory, divCpt);
            }
            //By default, show setting for yasr_most_or_highest_rated_posts
            else {
                yasrBuilderVvOptions (divOverallTxt, divSize, divView, divVotes, divUsername, divCategory, divCpt)
            }
            //be sure shortcodeAttributes is initialized again
            shortcodeAttributes =  yasrReturnShortcodeAttributes();
            shortcodeAttributes['name'] = event.target.value;
            shortcode = shortcodeAttributes['name'];
        }
        else {
            //use this filter to add new attributes
            filterShortcodeAttributes = wp.hooks.applyFilters('yasrBuilderFilterShortcode', shortcodeAttributes);

            //loop the shortcodeAttributes array from 'rows'
            //and if the key is found in filterShortcodeAttributes make the assigment
            for(let i=1; shortcodeAttributes.length; i++) {
                if(filterShortcodeAttributes.hasOwnProperty(shortcodeAttributes[i])) {
                    shortcodeAttributes[i] = filterShortcodeAttributes[i];
                }
            }

            shortcode =
                shortcodeAttributes['name']+
                shortcodeAttributes['rows']+
                shortcodeAttributes['view']+
                shortcodeAttributes['minvotesmost']+
                shortcodeAttributes['minvoteshg']+
                shortcodeAttributes['size']+
                shortcodeAttributes['txtPosition']+
                shortcodeAttributes['txt']+
                shortcodeAttributes['display']+
                shortcodeAttributes['category']+
                shortcodeAttributes['cpt'];

        }

        document.getElementById('yasr-builder-shortcode').textContent = '['+shortcode+']';
        document.getElementById('yasr-builder-copy-shortcode').setAttribute('data-shortcode', '['+shortcode+']');

        //If the previewButton was already clicked, and if the event is no the select, make fetch again
        if(previewClicked === true && event.target.id !== 'yasr-ranking-source' && event.target.name !== 'yasr-builder-category-radio') {
            yasrBuilderDoFetch(event);
        }
    });



    //event listener click on button
    copyButton.onclick = function (event) {
        let el = document.getElementById(event.target.id);
        copyToClipboard(el.getAttribute("data-shortcode"));
    }

    previewButton.onclick = function (event) {
        yasrBuilderDoFetch(event);
        previewClicked = true;
    }

    function yasrBuilderDoFetch(event) {
        const shortcode     = selectDataSource.value
        const fullShortcode = document.getElementById('yasr-builder-shortcode').textContent;
        fetch(ajaxurl +'?action=yasr_rankings_preview_shortcode&shortcode='+shortcode+'&full_shortcode='+fullShortcode)
            .then(response => {
                if (response.ok === true) {
                    return response.json();
                } else {
                    console.info(__('Ajax Call Failed. Shortcode preview can\'t be done', 'yet-another-stars-rating'));
                    return 'KO';
                }
            })
            .catch((error) => {
                console.info(error);
            })
            .then(response => {
                if (response !== 'KO') {
                    let newDiv = document.createElement('div');
                    newDiv.innerHTML = response;

                    //if a child already exists, replace it
                    if (previewDiv.childNodes.length > 0) {
                        previewDiv.replaceChild(newDiv, previewDiv.childNodes[0]);
                    } else {
                        previewDiv.appendChild(newDiv);
                    }
                }
            })
            .then(response => {
                if (shortcode === 'yasr_ov_ranking' || shortcode === 'yasr_most_or_highest_rated_posts') {
                    yasrDrawRankings();
                }
            })
    }

    /**
     * This function return the default array for shortcode attributes
     *
     * @return {{txt: string, size: string, txtPosition: string, name: string, rows: string}}
     */
    function yasrReturnShortcodeAttributes() {
        return {
            name: 'yasr_most_or_highest_rated_posts',
            rows:         '',
            size:         '',
            view:         '',
            minvotesmost: '',
            minvoteshg:   '',
            txtPosition:  '',
            txt:          '',
            display:      '',
            category:     '',
            cpt:          ''
        };
    }


    function yasrBuilderOvOptions (divOverallTxt, divSize, divView, divVotes, divUsername, divCategory, divCpt) {
        //show custom text for overall
        divOverallTxt.style.display = '';
        divSize.style.display       = '';
        divCategory.style.display   = '';
        divView.style.display       = 'none';
        divVotes.style.display      = 'none';
        divUsername.style.display   = 'none';
        if(divCpt !== null) {
            divCpt.style.display        = '';
        }

    }

    function yasrBuilderVvOptions (divOverallTxt, divSize, divView, divVotes, divUsername, divCategory, divCpt) {
        divView.style.display       = ''
        divVotes.style.display      = '';
        divSize.style.display       = '';
        divCategory.style.display   = '';
        divOverallTxt.style.display = 'none';
        divUsername.style.display   = 'none';
        if(divCpt !== null) {
            divCpt.style.display        = '';
        }
    }

    function yasrBuilderNoStarsOptions (divOverallTxt, divSize, divView, divVotes, divUsername, divCategory, divCpt) {
        divUsername.style.display   = '';
        divOverallTxt.style.display = 'none';
        divView.style.display       = 'none';
        divVotes.style.display      = 'none';
        divSize.style.display       = 'none';
        divCategory.style.display   = 'none';

        if(divCpt !== null) {
            divCpt.style.display        = 'none';
        }
    }

}