class singlePage {
    constructor() {
        this.attachEvents();
        this.searchListener();
        this.lazyloadInitialItems();
    }

    attachEventsLazyload() {
        $('.path .path-tabs li a').click(function() {
            const tab = $(this).attr('data-tab');
            $(this).parents('.path').find('.path-tab').hide();
            $(this).parents('.path').find(`.path-tab-${tab}`).show();
        });

        $('.path .code-tabs li a').click(function() {
            const tab = $(this).attr('data-tab');
            $(this).parents('.path-tab-coding').find('.tab-code').hide();
            $(this).parents('.path-tab-coding').find(`.tab-code-${tab}`).show();
        });

        $('.btn-model-example').click(function() {
            $(this).parents('.blocks-block').find('.model-example').show();
            $(this).parents('.blocks-block').find('.model-definition').hide();
        });
    
        $('.btn-model-definition').click(function() {
            $(this).parents('.blocks-block').find('.model-example').hide()
            $(this).parents('.blocks-block').find('.model-definition').show()
        });

        $('.api-path-try-btn').click(function() {
            const pathId = $(this).attr('data-id');
            window.zamaPopup.createRequest(pathId);
        });

        window.copyToClipboard = str => {
            const el = document.createElement('textarea');
            el.value = str;
            document.body.appendChild(el);
            el.select();
            document.execCommand('copy');
            document.body.removeChild(el);
        };

        window.attachClipboard = () => {
            $('*[data-copy]').off('click');
            $('*[data-copy]').click(function() {
                const value = $(this).attr('data-copy');
                window.copyToClipboard(value);
                $('.uk-tooltip.uk-active').text('Copied!');
            });

            $('.path pre code').after('<span class="copy" uk-tooltip="Click to copy">Copy</span>');
            $('.path pre .copy').off('click');
            $('.path pre .copy').click(function() {
                const ele = $(this);
                const value = $(ele).parents('pre').find('code').text();
                window.copyToClipboard(value);
                $('.uk-tooltip.uk-active').text('Copied!');
            });
        }
    }

    deattachEventsLazyload() {
        $('.path .path-tabs li a').off('click');
        $('.path .code-tabs li a').off('click');
        $('.btn-model-example').off('click');
        $('.btn-model-definition').off('click');
        $('.api-path-try-btn').off('click');
    }

    attachEvents() {
        let interval = null;
        let intervalLazyload = null;
        let lastActiveId = null;
        let lastActiveIdLazyload = null;

        $('main').scroll(() => {
            if (interval) {
                clearTimeout(interval);
            }

            if (intervalLazyload) {
                clearTimeout(intervalLazyload);
            }

            interval = setTimeout(() => {
                let currentActiveId = $('aside .uk-nav .uk-active a').attr('href');

                if (currentActiveId === lastActiveId) return;

                $('aside .uk-nav li')
                    .parents('.uk-parent')
                    .removeClass('uk-open')
                    .removeClass('uk-active')
                    .find('ul')
                    .attr('hidden', true);

                $('aside .uk-nav .uk-active')
                    .parents('.uk-parent')
                    .addClass('uk-open')
                    .find('ul')
                    .attr('hidden', false);

                lastActiveId = currentActiveId;
            }, 40);

            intervalLazyload = setTimeout(() => {
                const href = $('aside .uk-nav .uk-active a').attr('href');
                if (!href) return;
                let currentActiveId = href.replace('#', '');
                if (currentActiveId === lastActiveIdLazyload) return;

                const lazyPathIndex = pathsObject.paths.findIndex(({ id }) => id === currentActiveId);
                if (lazyPathIndex < 0) return;

                const lazyPaths = [];
                const pathsLength = pathsObject.paths.length;

                for ( let i = 1; i <= 3 && (lazyPathIndex - i) >= 0; i++ ) {
                    lazyPaths.push(pathsObject.paths[lazyPathIndex - i]);
                }

                lazyPaths.push(pathsObject.paths[lazyPathIndex]);

                for ( let i = 1; i <= 3 && (lazyPathIndex + i) < pathsLength; i++ ) {
                    lazyPaths.push(pathsObject.paths[lazyPathIndex + i]);
                }

                this.deattachEventsLazyload();

                $(`.lazyload-data`).html('');
                $(`.skeleton`).show();

                lazyPaths.forEach(lazyPath => {
                    const { id, lazyloadHTML = '' } = lazyPath;
                    if (!!lazyloadHTML) {
                        $(`.path-${id} .lazyload-data`).html(lazyloadHTML);
                        $(`.path-${id} .skeleton`).hide();

                        const code = $(`.path-${id} pre > code`);
                        code.each(function(i, e) { hljs.highlightBlock(e); });
                    }
                })

                this.attachEventsLazyload();

                lastActiveIdLazyload = currentActiveId;
            }, 500)
        });

        this.attachEventsLazyload();

        setTimeout(() => {
            $('.sidebar-loader').hide();
            $('.sidebar-loader').hide();
            $('.nav-top').show();
            $('header .links-inner').show();
            window.attachClipboard();
        }, 500);
    }

    lazyloadInitialItems(length = 3) {
        const lazyPaths = [];
        const pathsLength = pathsObject.paths.length;

        for ( let i = 0; i < length && i < pathsLength; i++ ) {
            lazyPaths.push(pathsObject.paths[i]);
        }

        lazyPaths.forEach(lazyPath => {
            const { id, lazyloadHTML = '' } = lazyPath;
            if (!!lazyloadHTML) {
                $(`.path-${id} .lazyload-data`).html(lazyloadHTML);
                $(`.path-${id} .skeleton`).hide();

                // const code = $(`.path-${id} pre > code`);
                // code.each(function(i, e) { hljs.highlightBlock(e); });
            }
        });
    }

    searchListener() {
        const lc = (str) => (str || '').toLowerCase();

        $('.search input.uk-search-input').on('input', async function() {
            const value = lc($(this).val());
        
            if (!value || value.length < 3) return $('.search-result').hide();
            const {paths = []} = pathsObject;
        
            const filteredData = paths.filter(({summary = '', pathName = '', tags = []}) => lc(summary).includes(value) || lc(pathName).includes(value) || lc(tags.join(' ')).includes(value));

            if (filteredData.length) {
                const searchItemsHtml = filteredData.map(({ id, summary, methodName,tags, pathName }) => (`
                    <a href="#${id}" onclick="$('.search-result').hide()">
                        <strong>${summary || `${(tags || []).join(',')}`}</strong><br />
                        <span><span class="api-method api-method-${lc(methodName)} uk-label">${methodName}</span> ${pathName}</span>
                    </a>
                `
                )).join('');
                $('.search-result div').html(searchItemsHtml)
                $('.search-result').show();
            } else {
                $('.search-result').hide();
            }
        });
    }
}

$(() => {
    new singlePage();
});