/*
 * Author       : Jai K
 * Purpose      : Server Down & Re-import scripts
 * Updated On   : 2017-03-20 18:34
 */

function initImport(){
                                                                
    $('#alt-import').removeClass('backup').fadeIn('slow');
    $('#alt-import-msg').fadeOut('slow', function(){
        $('#alt-import-pro, #alt-import .ctrl-btn').fadeIn();
        $('#alt-import .title h2').html('Importing ...');

        setTimeout(function(){
            importAjax();
            setTimer();
        }, 1500);

    });
};

function errImport(){
    $('#alt-import .title .ctrl-btn').trigger('click');
    
    $('#alt-import').fadeOut('slow');
    $('#alt-import-msg').fadeIn('slow', function(){
        $('#alt-import-msg .load-ico').removeClass('fa-spin fa-futbol-o fa-check').addClass('fa-times');
        $('#alt-import-msg > div').html('Sorry, Unable to connect to an alternative server!<div><button class="btn" id="try-again-btn">Try again</button></div>');
        $('#alt-import-dialog .close-btn').fadeIn('slow');
    });
    
    return false;
}
                                                            
function allImportDone(){
    
    var data = {
        act : 'completed',
    };
    
    $.post( baseURL + 'billing_common/import/', data, function(results){
        results = JSON.parse(results);
        
        if( results['err_no'] == '0' ) {
            errImport();
            return false;
        }
    
        
        $('#alt-import .ctrl-btn').fadeOut(1100, function(){
            $('#alt-timer').html('');
            $('#alt-import .title h2').html('Import: Completed');
            $('#alt-import-dialog .close-btn').fadeIn('slow');
            $('[name="server_down"]').iCheck('uncheck');
            
        });
        
    });
}

var timerInter = '';
function setTimer(step){
    var total   = parseInt($('#alt-import-total-cnt').text()) || 0
    ,   allDone = parseInt($('#alt-import-done-cnt').text()) || 0
    ,   step    = typeof step == 'undefined' ? 0 : Math.floor(step/1000)
    //,   secs    = Math.floor( (total-allDone) / 247 ) + step;
    ,   secs    = Math.floor( (total-allDone) / 350 ) + step;
    
    window.clearInterval(timerInter);
    timerInter = window.setInterval(function(){
        if( $('#alt-import .title .ctrl-btn').hasClass('fa-pause') ) {
            --secs;

            var str = ''
            ,   H   = Math.floor(secs/3600)
            ,   M   = Math.floor(secs/60)
            ,   S   = secs;
            
            if( H > 0 ) {
                // Hour
                str += H+'Hour ';
                M   = M % 3600; 
            }
            
            if( M > 0 ) {
                // Minutes
                str += M+'min ';
                S   = S % 60;
            }
            
            if( S > 0 ) {
                str += S+'sec';
            }
            
            if( str != '' ) {
                $('#alt-timer').html(str);
            }else {
                $('#alt-timer').html('1sec');
                window.clearInterval(timerInter);
            }
        }
    }, 1000);
    
}

function importAjax(){
    var step    = rand(1000, 900)
    ,   $act    = $('#alt-import tbody tr.active')
    ,   actRows = parseInt($act.attr('data-rows')) || 0
    ,   total   = parseInt($('#alt-import-total-cnt').text()) || 0
    ,   actDone = parseInt($act.attr('data-done')) || 0
    ,   inter   = '';
    
    step = step > actRows ? actRows : step;
    step = actDone+step > actRows ? actRows-actDone : step;   
    
    var $altImBtn = $('.alt-import-btn:first')
    ,   data    = {
        'act'   : 'import',
        'tbl'   : $act.attr('data-tbl'),
        'limit' : step, 
        
        'host'  : $altImBtn.attr('data-host') || "",
        'user'  : $altImBtn.attr('data-user') || "",
        'pass'  : $altImBtn.attr('data-pass') || "",
        'db'    : $altImBtn.attr('data-db') || "",
        
        'rec_clm': $act.attr('data-rec-clm') || "",
        'rec_nos': $act.attr('data-rec-nos') || "",
    };
    
    
    $.post( baseURL + 'billing_common/import/', data, function(results){
        results = JSON.parse(results);
        
        //console.log('Err. No: '+results['err_no']);
        if( results['err_no'] == '0' ) {
            errImport();
            return false;
        }
        
        $act.attr('data-rec-clm', results['rec_clm']);
        $act.attr('data-rec-nos', JSON.stringify( results['rec_nos'] ));
        
        actDone += step;
        $act.attr('data-done', actDone);
        $act.find('.now-done').html(actDone);    
            
        var allDone = parseInt($('#alt-import-done-cnt').text()) || 0;
        allDone += step;
        $('#alt-import-done-cnt').html( allDone );

        // Set Progress
        var isPaused = $('#alt-import .title .ctrl-btn').hasClass('fa-pause') ? false : true
        ,   percent = (allDone/total)*100;
        
        $('#alt-import-status-percent').html( ( percent < 100 ? percent.toFixed(2) : '100')+'%' );
        $('#alt-import-pro .pro-bar').animate({
            'max-width' : percent +'%'
        }, (isPaused ? 100 : step ));
        
        // Check for Marking as Done
        if( actDone >= actRows ) {
            // This row is completed
            $act.removeClass('active').addClass('done');
            $act.next().addClass('active');
            
            var $o = $('#alt-import tr.active');
            //if( $('#alt-import #plotter').offset().top < o && !$('#alt-import #plotter').is(':animated') && o > 0  ) {   
            if( $o.length > 0 ){
                $('#alt-import #plotter').stop().animate({ 
                    scrollTop: $o.offset().top - 250
                }, step);  
            }
        }

        if( allDone < total ) {
            // Loop again
            
            if( !isPaused ) {
                //if( step > 100 || (step < 100 && allDone % 165 == 0 ) ) {
                    setTimer(step);
                //}
                window.setTimeout(function(){
                    importAjax();
                }, step);
            }
            
        }else {
            // All are up to date and imported
            if( !$('#alt-import #plotter').is(':animated') ) {
                $('#alt-import #plotter').stop().animate({ 
                    scrollTop: 2000
                }, 1000);  
            }
            allImportDone();
        }

    });

}

$(document).ready(function () {
    
    $(document).on('click', '#try-again-btn', function(){
        if( $(this).attr('data-type') == 'init' ) {
            $('#alt-import-msg > div').html('Trying to connect ...');
            setTimeout(function(){ $('.alt-import-btn:first').trigger('click'); }, 1000);
            
        }else {
            $('#alt-import').fadeIn('slow');
            $('#alt-import-msg').fadeOut('slow', function(){
                setTimeout(function(){
                    $('#alt-import .title .ctrl-btn.fa-play').trigger('click');
                }, 1300);
            });
        }
        
    });
    
    $(document).on('click', '#alt-import .title .ctrl-btn', function(){
        
        if( $(this).hasClass('fa-pause') ) {
            // Pause
            window.clearInterval(timerInter);
            
            $(this).removeClass('fa-pause').addClass('fa-play');
            $('#alt-import .title h2').html('Import: Paused');
            $('#alt-import-pro .pro-bar').stop().animate({'background-color': '#FFC107'}, 0);
            $('#alt-import').addClass('paused');
            $('#alt-timer').fadeOut('slow');
            $('#alt-import-dialog .close-btn').fadeIn('slow');
        }else {
            // Play
            $(this).removeClass('fa-play').addClass('fa-pause');
            $('#alt-import .title h2').html('Importing ...');
            $('#alt-import-pro .pro-bar').css({'background-color': '#F33'});
            $('#alt-import').removeClass('paused');
            $('#alt-timer').fadeIn('slow');
            $('#alt-import-dialog .close-btn').fadeOut('slow');
            importAjax();
            
        }
        
    });
    
    $(document).on('click', '#alt-import-dialog .close-btn', function(){
        $('#alt-import .title .ctrl-btn.fa-pause').trigger('click');
        
        $('.alt-import-btn').removeAttr('data-load');
        $('.over-lay:first').fadeOut('slow');
        $('#alt-import-dialog').fadeOut('slow', function(){
            $(this).remove();
        });
    });
    
    $('.alt-import-btn').on('click', function(){
            
        var html = '';
        if( !$(this).attr('data-load') ) {
            html = '<div id="alt-import-dialog" class="popup-dialg">';
            html +=     '<i class="close-btn">&#10006;</i>';
            html +=     '<div id="alt-import" data-file="" >';
            html +=         '<div class="title"><h2> &nbsp;</h2> <span id="alt-timer">&nbsp;</span><span><i class="ctrl-btn fa fa-pause" style="display: none;"></i></span></div>';
            html +=         '<div id="alt-import-pro">';
            html +=             '<div class="pro-bar"></div>';
            html +=             '<div class="status"><span ><span id="alt-import-done-cnt">0</span> / <span id="alt-import-total-cnt">0</span></span> <span id="alt-import-status-percent">0%</span></div>';
            html +=         '</div>';    
            
            html +=         '<div id="plotter"><table style="width: 100%;"><tbody></tbody></table></div>';
            html +=      '</div>';
            
            html +=     '<div id="alt-import-msg" class="no-results"><i class="load-ico fa fa-spin fa-futbol-o"></i><div style="letter-spacing: 4px;" >Getting total counts ...</div></div>';
            html += '</div>';

            $('body').prepend(html);    
            $(this).attr('data-load', 'true');
        }
        
        var isBckup = $('#alt-import').hasClass('backup') ? true : false
        ,   data = {
                'act'   : isBckup ? 'backup' : 'total',
                'host'  : $(this).attr('data-host') || "",
                'user'  : $(this).attr('data-user') || "",
                'pass'  : $(this).attr('data-pass') || "",
                'db'    : $(this).attr('data-db') || "",
        };
        
        if( isBckup ) {
            data.url = $(this).attr('data-url') || "";
        }

        $.post( baseURL + 'billing_common/import/', data, function(results){

            results = JSON.parse(results) || "";
            
            if( results['err_no'] == '0' ) {
                $('#alt-import-msg .load-ico').removeClass('fa-spin fa-futbol-o').addClass('fa-times');
                $('#alt-import-msg > div').html('Sorry, Unable to connect to an alternative server!<div><button class="btn" id="try-again-btn" data-type="init">Try again</button></div>');
                $('#alt-import-dialog .close-btn').fadeIn('slow');
                return false;
            }else if( isBckup ) {
                // Backup is completed
                console.log('Backup is completed');
                $('#alt-import').removeClass('backup').attr('data-file', results['backup_path']);
                
                return false;
                
            }else {
 
                if( results == '' ) {
                    // All are upto date

                    $('#alt-import-pro, #alt-import .ctrl-btn').fadeOut();
                    $('#alt-import .title h2').html('&nbsp;');

                    $('#alt-import-msg').fadeIn('slow');
                    $('#alt-import-msg .load-ico').removeClass('fa-spin fa-futbol-o').addClass('fa-check');
                    $('#alt-import-msg > div').html('All are upto date!');
                    setTimeout(function(){ $('#alt-import-dialog .close-btn').fadeIn('slow'); }, 3000);
                    
                    $('[name="server_down"]').iCheck('uncheck');

                }else {
                    
                    var total   = 0
                    ,   html    = '';
                    Object.keys(results).map(function(k, v){

                        /*if( results[k]['TABLE_ROWS'] < 245 ) {
                            return true;
                        }*/

                        html += '<tr data-rows="'+ results[k]['TABLE_ROWS'] +'" data-tbl="'+ results[k]['table_name'] +'">';
                        html +=     '<td width="5%"><i class="fa fa-check"></i></td>';
                        html +=     '<td style="text-align: left;">'+ results[k]['table_name'] +'</td>';
                        html +=     '<td width="15%">'+ results[k]['TABLE_ROWS'] +'</td>';
                        html +=     '<td width="15%" class="now-done">-</td>';
                        html += '</tr>';

                        //html += '<div>'+ results[k]['table_name'] +'</div>';

                        total += parseInt( results[k]['TABLE_ROWS'] ) || 0;
                    });

                    $('#alt-import tbody').html(html);
                    $('#alt-import-total-cnt').html(total);

                    $('#alt-import tbody tr:first').addClass('active');

                    // Trigger Backup
                    setTimeout(function(){
                        $('#alt-import').addClass('backup');
                        $('#alt-import-msg > div').html('<span>Generating Backup ....</span><div class="pro-bar-wrap" style="text-align: center; padding-left: 44%; margin-top: 20px;"><div style="width: 140px; background: #eee; min-height: 3px;"><div class="pro-bar" style="background: #1ba; min-height: 3px; width:0px; "></div></div></div>');
                    
                        $('.alt-import-btn:first').trigger('click');
                        
                            var total   = parseInt($('#alt-import-total-cnt').text()) || 0
                            ,   secs    = Math.floor( total / 165 ) 
                            ,   runner  = secs * 100;
                            
                            if( secs > 0 ) {
                                
                                var i   = 0
                                ,   subInter = window.setInterval(function(){
                                        //console.log('Run: '+ runner);

                                        if( runner <= 0 ) {
                                            if( !$('#alt-import').hasClass('backup') ) {
                                                // Actual ajax backup is done
                                                window.clearInterval(subInter);
                                                
                                                $('#alt-import-msg .pro-bar-wrap').fadeOut('slow', function(){
                                                    var filePath = $('#alt-import').attr('data-file') || "";
                                                    
                                                    if( filePath == '' ) {
                                                        $('#alt-import-msg .load-ico').removeClass('fa-spin fa-futbol-o').addClass('fa-times');
                                                        $('#alt-import-msg span').html('Backup is failed! <div class="alt-msg" style="text-align: left; letter-spacing: 1px; padding: 20px; background: rgba(120, 120, 120, 0.1); width: 50%; margin: 20px auto;">Please ensure the following, <ul><li>DB connection parameters are correct</li><li>MySQL BIN: "c:\\xampp\\mysql\\bin"</li><li>Exec function is not disabled in "php.ini"</li></ul> <div style="border-bottom: 1px solid; width: 225px; cursor: pointer; position: absolute; left: 40%; margin-top: 30px;" onclick="initImport();">Proceed Import without backup</div></div>');
                                                        
                                                    }else {
                                                        
                                                        $('#alt-import-msg .load-ico').removeClass('fa-spin fa-futbol-o').addClass('fa-check');
                                                        $('#alt-import-msg span').html('Backup is completed');
                                                        $('#alt-import').append('<div  id="backup-file" class="alt-msg" style="text-align: center; color: #999; font-size: 12px; margin-top: 10px; letter-spacing: 1px;">Backup file: <a href="'+ filePath +'" target="_blank" style="color: #ccc; font-size: 12px;">'+filePath+'</a></div>');

                                                        setTimeout(function(){
                                                            initImport();
                                                        }, 2500);
                                                    }
                                                });
                                                
                                            }
                                            
                                            return false;
                                            
                                        }else if( runner < 10 ) {
                                            if( $('#alt-import').attr('data-file') != '' ) {
                                                $('#alt-import-msg span').html('Almost done, please wait ...');
                                            }
                                            
                                        }else if( !$('#alt-import').hasClass('backup') && $('#alt-import').attr('data-file') == '' ) {
                                            
                                            // Actual ajax backup is done && Backup is failed
                                            runner = 0;
                                        }

                                        $('#alt-import-msg .pro-bar').css({
                                           'width' : (++i) + '%'
                                        });

                                        runner -= secs;
                                    
                                }, 100);
                                
                            }
                        
                    }, 1500); 
                   //initImport();
                   
                   
                }
            }

        }); // Ajax
        
        $('.over-lay:first').fadeIn('slow');
        $('#alt-import-dialog').fadeIn('slow');
        return false;
    });

    //Timepicker
    $(".timepicker").timepicker({
        showInputs: false
    });

    //Colorpicker
    //$(".my-colorpicker2").colorpicker();
    

    //Loader
    $('button[data-loading-text]').on('click', function () {
        var btn = $(this);
        getSync();


    });
    $.validator.addMethod("date_val", function (value, element) {
        var return_val = true;
        var start_date = $('.start_date').val();
        var end_date = $('.end_date').val();
        if (start_date > end_date) {
            return_val = false;
        }
        return return_val;
    });

    $('form[name="settings"]').validate({
        errorElement: "li",
        errorLabelContainer: '.error_container',
        validClass: 'valid',
        focusInvalid: true,
        rules: {
            temple_name: {
                required: true
            },
            comp_email: {
                email: true
            },
            address: {
                required: true
            },
            contact_email: {
                email: true
            },
            contact_no: {
                required: true
            },
            fax: {
                valid_phone: true
            }
        },
        messages: {
            temple_name: {
                required: 'Please enter Temple Name!'
            },
            comp_email: {
                email: 'Please enter Company Email!'
            },
            address: {
                required: 'Please enter Address!'
            },
            contact_email: {
                email: 'Please enter Contact Email!'
            },
            contact_no: {
                required: 'Please enter Contact Number'
            },
            fax: {
                valid_phone: 'Please enter valid Contact Fax!'
            }
        }
    });

    $('form[name="general_settings"]').validate({
        errorElement: "li",
        errorLabelContainer: '.error_container',
        validClass: 'valid',
        focusInvalid: true,
        rules: {
            year_end_month: {
                required: true
            },
            gst: {
                required: true
            }
        },
        messages: {
            year_end_month: {
                required: 'Please select Month!'
            },
            gst: {
                required: 'Please enter GST!'
            }
        }
    });

    $.validator.addMethod("empty_logo", function (value, element) {
        var return_val = true;
        var upload_image = $('input[name="image"]').attr('data-value');
        if (upload_image == '') {
            return_val = false;
        }
        return return_val;
    });

    $.validator.addMethod("empty_login_image", function (value, element) {
        var return_val = true;
        var upload_image = $('input[name="login_image"]').attr('data-value');
        if (upload_image == '') {
            return_val = false;
        }
        return return_val;
    });

    $('form[name="design_settings"]').validate({
        errorElement: "li",
        errorLabelContainer: '.error_container',
        validClass: 'valid',
        focusInvalid: true,
        rules: {
            logo: {
                empty_logo: true
            },
            login_image: {
                empty_login_image: true
            }
        },
        messages: {
            logo: {
                empty_logo: 'Please select Logo!'
            },
            login_image: {
                empty_login_image: 'Please select Login Image!'
            }
        }
    });
});

function getSync() {
    var post_url = $('.sync_url').val();
    var request = $.ajax({        
        url: base_url + "general_settings/readHTML",
        type: 'POST',
        data: {post_url:post_url},
        dataType: "html",
        beforeSend: function () {
            $('button[data-loading-text]').button('loading');
            console.log('beforeSend');
            $('.inprogress').show();            
            $('.completed').hide(); 
            $('#myModal').modal('show');            
                       
            //alert('start');
        },
        success: function (data) {
            //alert('Success');            
            console.log(data);
        },
        complete: function () {
            $('.inprogress').hide();            
            $('.completed').show(); 
            $('.modal-footer').show(); 
            //alert('Synchronos Completed');
            //$('#myModal').modal('hide');
            $('button[data-loading-text]').button('reset');
        },
        error: function () {
            alert('Error');
        },
    });
}