<?php
Yii::app()->clientScript->registerCoreScript('jquery.ui');
cs()->registerScriptFile(Yii::app()->baseUrl . '/js/plDialog/plDialog.js', CClientScript::POS_HEAD);
$this->widget('ext.PlGrid.PlGridView', array(
    'id' => 'third-party-credentials-grid',
    'headerTitle' => 'Sozial_Credentials', // optional
    'addButtonTitle' => 'PHONESETTINGSCREDENTIALS_SOZIAL_CREDENTIALS_ADD_BTN',
    'modalCreateHeader' => 'THIRDPARTYCREDENTIAL_MODEL_HEADER_CREATE', // optional
    'createInModal' => true,
    'enableSearchButton' => false,
    'itemsCssClass' => 'plTable items',
    'dataProvider' => $model->search(),
    'filter' => $model,
    'columns' => array(
        array(
            'value' => array($this, 'renderAuthenticatedStatus'),
            'name' => 'authenticated',
            'headerHtmlOptions' => array(
                'data-translation-id' => 'THIRDPARTYCREDENTIAL_MODEL_TITLE_AUTHENTICATED',
                'style' => 'width: 120px'
            ),
        ),
        array(
            'value' => array($this, 'renderPasswordStatus'),
            'name' => 'passwordStatus',
            'headerHtmlOptions' => array(
                'data-translation-id' => 'THIRDPARTYCREDENTIAL_MODEL_TITLE_PASSWORD_STATUS',
                'style' => 'width: 100px'
            ),
        ),
        array(
            'type' => 'raw',
            'name' => 'title',
            'value' => array($this, 'renderTitle'),
            'headerHtmlOptions' => array('data-translation-id' => 'THIRDPARTYCREDENTIAL_MODEL_TITLE'),
        ),
        array(
            'name' => 'addressBookName',
            'headerHtmlOptions' => array('data-translation-id' => 'THIRDPARTYCREDENTIAL_MODEL_ADDRESSBOOK_NAME'),
        ),
//        array(
//            'name' => 'calendarName',
//            'headerHtmlOptions' => array('data-translation-id' => 'THIRDPARTYCREDENTIAL_MODEL_ADDRESSBOOK_NAME'),
//        ),
        array(
            'name' => 'updated',
            'value' => array($this, 'renderUpdated'),
            'headerHtmlOptions' => array('data-translation-id' => 'THIRDPARTYCREDENTIAL_MODEL_UPDATED'),
        ),
        array(
            "cssClassExpression" => function($index, $data) {

                if ($data->hasRunningJob()) {
                    return "running";
                }
                return "";
            },
            'template' => '{ajaxPassword}{sync}{delete}',
            'class' => 'ext.PlGrid.PlCButtonColumn',
            'htmlOptions' => array(
                'style' => 'width: 55px',
                'data-translation-id' => 'THIRDPARTYCREDENTIAL_MODEL_IMPORT_ADDRESSES',
            ),
            'buttons' => array(
                'sync' => array(
                    "class" => "sync",
                    'icon' => 'exchange',
                    'label' => __('THIRDPARTYCREDENTIAL_MODEL_IMPORT_ADDRESSES'),
                    'url' => 'Yii::app()->createUrl("phonesettingsThirdPartyCredentials/default/startSingleAccountImport", array("id"=>$data->id))',
                ),
                'ajaxPassword' => array(
                    'label' => '<i class="icon-pencil"></i>',
                    'imageUrl' => false,
                    'options' => array(
                        'title' => __('THIRDPARTYCREDENTIAL_PASSWORD_BUTTON'),
                        'data-translation-id' => 'THIRDPARTYCREDENTIAL_PASSWORD_BUTTON',
                    ),
                    'url' => 'Yii::app()->createUrl("phonesettingsThirdPartyCredentials/default/ajaxPassword", array("id"=>$data->id))',
                    'click' => 'js:function(){
                            if ($(this).parent().parent().find(".icon-cloud").length === 1) {
                                    $.get(this.href, function(data){
                                        $("#third-party-credentials-grid_Modal .modal-body").html(data);
                                        $("#third-party-credentials-grid_Modal .modal-header h4")
                                            .html("' . __('THIRDPARTYCREDENTIAL_PASSWORD_HEADER_UPDATE') . '");
                                        $("#third-party-credentials-grid_Modal").modal("show");
                                        return false;
                                    });
                            }
                            return false;
                        }',
                )
            ),
        ),
    ),
        )
);

if (app()->user->translateMode) {
    $this->renderPartial('_translationTags');
}
?>
<script>
    var defaultOnMessage = ws.onmessage;
    ws.onmessage = function (e) {
        var msg = jQuery.parseJSON(e.data);
        switch (msg.name) {
            case "login":
                console.log(msg);
                subscribeJobChangeEvents();
                break;
            case "jobChanged":
                console.log(msg);
                updateGrid(msg.data.job);
                break;
            case "":
                console.log("login failed !");
            default:
                defaultOnMessage(e);
        }
    };

    function subscribeJobChangeEvents()
    {
        ws.command({
            name: "subscribeJobEvents",
            type: "command",
            uuid: ws.generateUUID()
        });
    }
    initGridJobState();
    function initGridJobState()
    {
        $("#third-party-credentials-grid").find(".running").each(function (_, e) {
            var buttonnCell = $(e);
            var syncLink = buttonnCell.find(".icon-exchange").parent();
            var syncLink = buttonnCell.find(".sync");
            if (syncLink.find("i").length) {
                syncLink.find("i").remove();
                syncLink.append("<img src='../img/loading.gif' />");
            }
        });
    }

    function updateGrid(job)
    {
        var meta = $.parseJSON(job.meta);
        var id = meta.thirdPartyCredentialId;
        var jobStatusRunning = <?php echo Job::Running; ?>;
        var jobStatusFinished = <?php echo Job::Finished; ?>;
        var jobStatusFailed = <?php echo Job::Failed; ?>;

        var syncLink = $(".sync[href*='" + id + "']");
        if (parseInt(job.status) === jobStatusRunning) {
            var syncLink = $(".sync[href*='" + id + "']");
            syncLink.attr("data-original-title", meta.progress + "%");
            syncLink.parent().find(".tooltip-inner").text(meta.progress + "%");
            if (syncLink.find("i").length) {
                syncLink.find("i").remove();
                syncLink.append("<img src='../img/loading.gif' href='#?" + id + "'/>");
            }
        } else if (parseInt(job.status) === jobStatusFinished || parseInt(job.status) === jobStatusFailed) {
            if (syncLink.find("img").length) {
                syncLink.find("img").remove();
                syncLink.attr("data-original-title", "<?php echo __("THIRDPARTYCREDENTIAL_MODEL_IMPORT_ADDRESSES"); ?>");
                syncLink.parent().find(".tooltip-inner").text("<?php echo __("THIRDPARTYCREDENTIAL_MODEL_IMPORT_ADDRESSES"); ?>");
                syncLink.append($("<i />").addClass("icon-exchange"));
            }
        }
    }
</script>