jQuery(document).ready(function ($) {

    var form = $('#webien-search-build-cache');
    var offset = 0;
    var total = 0;
    var buildTimer = 0;
    var buildInterval;


    form.find('#build-cache-btn').on('click', function(){

        form.find('.progress').show();

        do_search(offset, true);

        buildInterval = setInterval(function(){
            buildTimer++;
        }, 1000);

        return false;
    });

    function do_search(offset, first){
        $.ajax({
            url: ajaxurl,
            data: {
                action: 'webien_build_cache',
                offset: offset,
                first: first,
                total: total
            },
            success: function (resp) {

                if(resp.data.activate !== undefined){
                    $('div[data-name="webien_search_index_message"]').css({'opacity':0.5, 'pointer-events':'none'});
                    alert('Spara om innan du fortsätter med detta.');

                    return;
                }

                var percent = (resp.data.nextoffset/total)*100;
                percent = Math.round((percent + Number.EPSILON) * 100) / 100;

                if(percent > 100){
                    percent = 100;
                }


                // Update progress bar
                form.find('.bar').css({'width':percent+'%'});

                var complete = resp.data.nextoffset;
                if(complete > total){
                    complete = total;
                }

                if(!first){
                    // Estimated time left

                    var totalTime = ((buildTimer/percent)*100);
                    var timeLeft = secondsToHms(totalTime-(totalTime*(resp.data.nextoffset/total)));
                    form.find('.status').html('Status: '+complete+'/'+total+' ('+percent+'%'+'), beräknad tid kvar: '+timeLeft);

                }


                if(resp.data.islast === true){
                    form.find('textarea').append('---------- KLART! ----------' +'\n');
                    form.find('textarea').scrollTop(form.find('textarea')[0].scrollHeight);
                    form.find('.status').html('Status: '+complete+'/'+total+' ('+percent+'%'+')');
                    clearInterval(buildInterval);


                    return false;
                }
                if(first){
                    total = parseFloat(resp.data.total);
                    form.find('textarea').append(resp.data.msg +'\n');
                    form.find('textarea').append('Bygger upp cache..' +'\n');
                    form.find('textarea').scrollTop(form.find('textarea')[0].scrollHeight);
                }

                offset = parseFloat(resp.data.nextoffset);

                do_search(offset, false);

            }
        });
    }


    // Clear cache btn
    $('#clear-cache-btn').on('click', function(){
        $('.clear-all-cache-loader').removeClass('done');
        $('.clear-all-cache-loader').addClass('loading');
        $.ajax({
            url: ajaxurl,
            data: {
                action: 'webien_clear_all_cache'
            },
            success: function (resp) {
                $('.clear-all-cache-loader').removeClass('loading');
                $('.clear-all-cache-loader').addClass('done');
                setTimeout(function(){
                    $('.clear-all-cache-loader').removeClass('done');
                }, 2000);
            }
        });
        return false;
    });

    function secondsToHms(d) {
        d = Number(d);
        var h = Math.floor(d / 3600);
        var m = Math.floor(d % 3600 / 60);
        var s = Math.floor(d % 3600 % 60);

        var hDisplay = h > 0 ? h + (h == 1 ? "h, " : "h, ") : "";
        var mDisplay = m > 0 ? m + (m == 1 ? "m, " : "m, ") : "";
        var sDisplay = s > 0 ? s + (s == 1 ? "s" : "s") : "";
        return hDisplay + mDisplay + sDisplay;
    }
});