
function millisecondsToTime(duration) {

    var milliseconds = Math.floor((duration % 1000) / 100),
        seconds = Math.floor((duration / 1000) % 60),
        minutes = Math.floor((duration / (1000 * 60)) % 60),
        hours = Math.floor((duration / (1000 * 60 * 60)) % 24);

    var str = hours + " hour"+((hours<=1)?"":"s")+", " 
            + minutes + " minute"+((minutes<=1)?"":"s")+", " 
            + seconds + " second"+((seconds<=1)?"":"s");

    return str;
}

$(document).ready(function () {

    $('#stop_process_btn').click(function (event) {
        localStorage.setItem('stop_process', 1);
    });

    $('#start_process').click(function (event) {
        var conf = confirm("Are you sure to the start process over?");
        localStorage.setItem('stop_process', 0);
        localStorage.setItem('new_process', 0);
        if (conf) {
            return true;
        } else {
            return false;
        }
    });

    $('#start_new_process').click(function (event) {
        var conf = confirm("Are you sure to start a new process?");

        if (conf) {

            localStorage.setItem('stop_process', 0);
            localStorage.setItem('new_process', 1);

            $('.progress-bar').attr('aria-valuenow', 0);
            $('.progress-bar').width('0%');
            $('.progress-bar').html('0%');

            return true;
        } else {
            return false;
        }
    });

    localStorage.setItem('stop_process', 0);

    var total_page = 0;
    var fetchComplete = false;
    var completedNumber = 0;
    var serial = 1;
    var progress = 0;
    var progressPerRequest = 0;

    $(document).on('submit', '#process-form', function (e) {
        e.preventDefault();
        $('.generation-msg').html('');

        var new_process = localStorage.getItem('new_process');

        if (new_process == 1) {

            completedNumber = 0;
            serial = 1;
            progress = 0;
            progressPerRequest = 0;
            
            $('.progress-bar').attr('aria-valuenow', 0);
            $('.progress-bar').width('0%');
            $('.progress-bar').html('0%');
        }

        var data = $("#process-form").serialize();
        data += '&action=count_user';

        $('.progress').show();
        $.ajax({
            type: 'POST',
            url: 'action.php',
            data: data,
            dataType: 'json',
            async: true,
            success: function (result) {
                var counter = result.counter;
                var error = result.error;
                if (error) {
                    alert(error);
                    return false;
                }
                // per request
                total_page = Math.ceil(counter / 10);
                progressPerRequest = (100 / total_page);

                if (new_process == 1) {

                    setTimeout(() => {
                        getRecord();
                    }, 600);

                } else {

                    getRecord();
                }

            }
        });

    });

    function getRecord() {

        $('.progress-bar').addClass('active');
        $('.progress-bar').addClass('progress-bar-striped');

        var stop_process = localStorage.getItem('stop_process');
        if (stop_process == 1) {
            alert('You stopped the process!')
            return false;
        }

        var data = $("#process-form").serialize();
        data += '&action=creating_bill&completed=' + completedNumber;

        var time_took = new Date();

        $.ajax({
            type: 'POST',
            url: 'action.php',
            data: data,
            dataType: 'json',
            async: true,
            success: function (result) {

                $.each(result, function (index, item) {
                    $('.generation-msg').append('<li>' + item.message + '</li>');
                    serial = serial + 1;

                    $("#generation-result").animate({
                        scrollTop: $('#generation-result')[0].scrollHeight
                    }, 0);

                });

                progress = progress + progressPerRequest;

                time_took = new Date() - time_took;

                var exists = total_page - completedNumber;

                var need_more = (exists * time_took);
                $('#seconds_left').text(millisecondsToTime(need_more) + ' left.');

                $('.progress-bar').attr('aria-valuenow', Math.floor(progress));
                $('.progress-bar').width(Math.floor(progress) + '%');
                $('.progress-bar').html(Math.floor(progress) + '%');
                if (Math.floor(progress) == 100) {
                    $('.progress-bar').removeClass('active');
                    $('.progress-bar').removeClass('progress-bar-striped');
                }
                completedNumber = completedNumber + 1;
                if (completedNumber < total_page) {
                    getRecord();
                } else {
                    $('.progress-bar').attr('aria-valuenow', 100);
                    $('.progress-bar').width('100%');
                    $('.progress-bar').html('100%');
                    $('.progress-bar').removeClass('active');
                    $('.progress-bar').removeClass('progress-bar-striped');
                }
            }
        });
    }
});
