"use strict";

class App {
    constructor() {
        this.csrf_token = $('#csrf_token').val();
        this.currentPercentage = 0;
        this.id_campaign = parseInt(getUrlParam('campaign'));
        this.myInterval = 0;
        this.progressPercentageStep = 100 / parseInt($('#startCampaign').attr('data-remaining_qty'));
        this.sentRecipientsQty = 0;
        this.smtpid = 0;
        this.requests = 0;
        this.totalRecipients = parseInt($('#startCampaign').attr('data-remaining_qty'));
    }
    addBackgroundAdminInfoAction() {
        $('#backgroundinfo *').on('click', function() {
            if ($('#backgroundProcess').parent().hasClass('checked')) {
                $('#admininfo').slideDown(200);
            } else {
                $('#admininfo').slideUp(200);
            }
        });
    }
    addStopSendingAction() {
        $('#stopCampaign').on('click', () => {
            this.stop_sending();
            $.ajax({
                type: 'POST',
                url: 'index.php?manage=campaign&adata=modify&action=stop.ajax',
                async: true,
                data: {
                    id_campaign: this.id_campaign,
                    adata: '1'
                },
                success: function(response) {
                    if (response.indexOf('Error') > -1){
                        $('#progres_info').html(response);
                        alert(response);
                    } else {
                        location.href="index.php?manage=campaign&action=proceed";
                    }
                }
            });
            location.reload();
        });
    }
    addMultiSmtpSupport() {
        $('#multi_smtp_group *').on('click', () => {
            var multi = $('#multi_smtp').is(':checked');
            if (multi) {
                $('#single').addClass('hidden');
                $('#multi').removeClass('hidden');
            } else {
                $('#multi').addClass('hidden');
                $('#single').removeClass('hidden');
            }
        });
    }
    progress_belt(perc) {
        perc = Math.floor(perc);
        $('.progress-bar').css('width', perc+'%').attr('aria-valuenow', perc).html(perc + '%');  
    }

    stop_sending() {
        clearInterval(this.myInterval);
    }

    koniec(qty) {
        this.stop_sending();
        $('#progres_info').html(lang_campaign_sent + ' ' + qty + ' ');
        $('#listCampaign').css({ display: 'block' });
        $('#stopCampaign').css({ display: 'none' });
        $.ajax({
            type: 'POST',
            url: 'index.php?manage=campaign&adata=modify&action=finish',
            async: true,
            data: {
                id_campaign: this.id_campaign,
                adata: '1',
                csrf_token: this.csrf_token
            }
        });
    }
}
const app = new App();

        
$(document).ready(function() {
    app.addBackgroundAdminInfoAction();
    app.addMultiSmtpSupport();
    app.addStopSendingAction();
    
    addStartClickAction();
});

function addStartClickAction() {
    $('#startCampaign').on('click', function() {
        var useSMTP = $('#startCampaign').attr('data-use_smtp');
        if (useSMTP == 1) {
            var smtpVal = ($('select[name=smtpid]').val()).split(":");
            var time_interval = (60 * 60 * 1000) / parseInt(smtpVal[1]);
            var smtpid = parseInt(smtpVal[0]);
        } else {
            var time_interval = (60 * 60 * 1000) / parseInt($('#startCampaign').attr('data-limit_per_hour'));
        }
        
        var multi_smtp = $('#multi_smtp').is(':checked') ? 1 : 0;
        var multi_limit = 0;
        
        if (multi_smtp == 1) {
            var smtp_arr = $("input[name='smtp_arr[]']:checked");
            var maxlimit = 0;
            var limitPerHour = 1;
            $.each(smtp_arr, function() {
                maxlimit = parseInt($(this).attr('data-limit'));
                limitPerHour = limitPerHour == 1 ? maxlimit : (maxlimit <= limitPerHour ? maxlimit : limitPerHour);
            });
            time_interval = ((60 * 60 * 1000) / limitPerHour);
        }
        
        // if no smtp selected
        if ( (multi_smtp == 1 && smtp_arr.length == 0) || (smtpid == 0 && useSMTP == 1 && !multi_smtp) ) {
            alert(lang_campaign_smtp);
            return;
        }
        
        if ($('#backgroundProcess').is(':checked')) {
            if (confirm(lang_campaign_bg_confirm_txt)) {
                send_email_background(smtpid, multi_smtp);
                $('#go_to_list').css({display: 'block'});
                $('#startCampaign').css({display: 'none'});
            }
        } else {
            $(this).addClass('disabled');
            $('#progres_info').html(lang_campaign_server_connecting);
            $('#stopCampaign').css({ display: 'block' });
            $('#startCampaign').css({ display: 'none' });
            if (multi_smtp == 1) {
                app.myInterval = setInterval( function () {
                    $.each(smtp_arr, function() {
                        send_email(parseInt($(this).val()));
                    });
                }, time_interval);
            } else {
                app.myInterval = setInterval( function () {
                    send_email(smtpid);
                }, time_interval);
            }
        }
        
    });
}

function send_email_background(smtpid, multi_smtp) {
    var emailToAdmin = $('#emailToAdmin').val();
    var adminNotify = $('#adminNotification').is(':checked') ? 1 : 0 ;
    var smtp_arr = []
    
    $("input[name='smtp_arr[]']:checked").each(function () {
        smtp_arr.push(parseInt($(this).val()));
    });

    $.ajax({
        type: 'POST',
        url: 'index.php?manage=campaign&adata=modify&action=run.background',
        async: true,
        data: {
            id_campaign: app.id_campaign,
            adata: '1',
            csrf_token: app.csrf_token,
            smtpid: smtpid,
            email_admin: emailToAdmin,
            notify_admin: adminNotify,
            multi_smtp: multi_smtp,
            smtp_arr: smtp_arr
        },
        success: function(response) {
            if (response.indexOf('Error') > -1){
                $('#progres_info').html(response);
                alert(response);
            } else {
                location.href="index.php?manage=campaign&action=proceed";
            }
        }
    });
}

function send_email(smtpid) {
    $.ajax({
        type: 'POST',
        url: 'index.php?manage=campaign&adata=modify&action=run',
        data: {
            id_campaign: app.id_campaign,
            adata: '1',
            csrf_token: app.csrf_token,
            smtpid: smtpid
        },
        success: (response) => {
            app.sentRecipientsQty ++;
            app.currentPercentage = app.currentPercentage + app.progressPercentageStep;
            
            if (response.indexOf('quota') > -1){
                console.log(response);
                $('#progres_info').html(response);
                app.stop_sending();
            }
            
            if (response.indexOf('Error') > -1){
                console.log(response);
            } else {
                if (response == 'stop') {
                    app.stop_sending();
                    app.progress_belt('100');
                    app.koniec(app.sentRecipientsQty - 1);
                } else {
                    app.progress_belt(app.currentPercentage);
                    $('#progres_info').html(lang_campaign_sending + ' (' + app.sentRecipientsQty + '/' + app.totalRecipients + '), ' + lang_campaign_please_wait);
                }
            }
            if (app.sentRecipientsQty >= app.totalRecipients){
                app.stop_sending();
                app.progress_belt('100');
                app.koniec(app.totalRecipients);
            }
            
        }
    });
}



