<?php
if (isset($_POST['Sysconfig'])) {
    echo '<h4>' . __("SYSTEM_GLOBAL_CONFIG_MESSAGING_CHANGES_SAVED_SUCCESSFULLY") . '</h4>';
}
echo '<span>' . __("SYSTEM_GLOBAL_SEND_TEST_EMAIL_TO_CHECK_CONFIG") . '</span>';

/** @var BootActiveForm $form */
$form = $this->beginWidget(
        'bootstrap.widgets.TbActiveForm', array(
    'id' => 'email-test-form',
    'action' => array('systemGlobalConfig/default/sendTestMail'),
    'type' => 'inline',
    //'enableAjaxValidation'=>true,
    'enableClientValidation' => true,
    'clientOptions' => array('validateOnSubmit' => true),
    'htmlOptions' => array('style' => 'margin: 8px 0 0')
        )
);

$mailModel = new EMail();
$mailModel->recipient = app()->user->sudoUserInstance->email;
echo $form->emailField(
        $mailModel, 'recipient', array(
    'class' => 'span3',
    'placeholder' => "test@example.com",
    'required' => true,
    'data-translation-id' => 'EMAILS_MODEL_TO_MAILBOX'
        )
);

$this->widget('bootstrap.widgets.TbButton', array(
    'buttonType' => 'ajaxSubmit',
    'label' => __('GENERAL_SEND_BUTTON'),
    'url' => array('default/sendTestMail'),
    'htmlOptions' => array(
        'id' => 'sendMailBtn',
        'data-translation-id' => 'GENERAL_SEND_BUTTON',
    ),
    'loadingText' => __('SYSTEM_GLOBAL_SENDING_TEST_EMAIL'),
    'ajaxOptions' => array(
        'dataType' => 'json',
        'success' => 'js:function(data, textStatus, jqXHR){
			            console.log(data);
			            if(data.length != 0){
			                jQuery.each(data, function(key, value) {
			                    jQuery("#"+key+"_em_").show().html(value.toString());
			                    jQuery("#"+key).addClass("clsError");
			                    jQuery("label[for="+key+"]").addClass("clsError");
			                    //$("#sendMailBtn").button("reset");
			                });
			            };

			            if(jqXHR.status == 202){
			                console.log("202 found");
			                checkSendState(data.id);
			            };

			        }',
    )
));

echo $form->error($mailModel, 'to_mailbox');
echo $form->errorSummary($mailModel);

$this->endWidget();
?>

<script>
    $('#sendMailBtn').click(function () {
        var btn = $(this);
        btn.button('loading'); // call the loading function
    });

    var emailId;
    var previousState = -1;

    function stateChanged(state) {
        var changed = !(previousState == state);
        previousState = state;
        return changed;
    }

    function displayMessageForState(state, errorText) {
        if (!stateChanged(state)) {
            return;
        }
        var message = '';
        switch (state) {
            case 0:
                message = '<?php echo __('EMAIL_STATE_PENDING'); ?>';
                break;
            case 1:
                message = '<?php echo __('EMAIL_STATE_QUEUED'); ?>';
                break;
            case 2:
                message = '<?php echo __('EMAIL_STATE_SENDING'); ?>';
                break;
            case 3:
                message = '<?php echo __('EMAIL_STATE_SENT'); ?>';
                break;
            case 4:
                message = '<?php echo __('EMAIL_STATE_FAILED'); ?>';
                if (errorText.length > 1) {
                    message += " (" + errorText + ")";
                }
                break;
            default:
                message = '';
        }
        $('.alert').append("<br/><span>" + message + "</span>");
    }

    function checkSendState(id) {
        if (id != undefined) {
            emailId = id;
        }
        $.ajax({
            //Use an ABSOLUTE reference to your target webservice
            url: "<?php echo url('systemGlobalConfig/default/checkTestMail', array('id' => '')) ?>" + emailId,
            type: "GET",
            dataType: "json",
            data: {},
            success: function (data, textStatus, jqXHR) {
                if (data.state != undefined) {
                    displayMessageForState(data.state, data.error);

                    switch (data.state) {
                        case 0:
                        case 1:
                        case 2:
                            setTimeout(checkSendState, 1000);
                            break;
                        case 4:
                            $('.alert').removeClass('alert-info').addClass('alert-error');
                            $('.alert h4').text('<?php echo __('SYSTEM_GLOBAL_TEST_EMAIL_SENT_FAILED'); ?>');
                            $('.alert span')
                                    .first()
                                    .text('<?php echo __('SYSTEM_GLOBAL_TEST_EMAIL_CHECK_YOUR_CONFIG'); ?>');
                            $("#sendMailBtn").button("reset");
                            break;
                        case 3:
                            $('.alert').removeClass('alert-info').addClass('alert-success');
                            $('.alert h4').text('<?php echo __('SYSTEM_GLOBAL_TEST_EMAIL_SENT_SUCCESSFULY'); ?>');
                            $('.alert span')
                                    .first()
                                    .text('<?php echo __('SYSTEM_GLOBAL_TEST_EMAIL_CHECK_YOUR_INBOX'); ?>');
                            $("#sendMailBtn").button("reset");
                            break;
                        default:
                            setTimeout(checkSendState, 1000);
                    }
                } else {
                    setTimeout(checkSendState, 1000);
                }
            },
            //complete: checkSendState,
            timeout: 5000,
            contentType: "text/xml; charset=\"utf-8\"",
            async: true,
            error: function (xhr) {
                setTimeout(checkSendState, 5000);
            }
        });
    }
</script>