<?php
$this->widget('ext.PlGrid.PlGridView', array(
    'id' => 'gateway-grid',
    'headerTitle' => 'Header_title', // optional
    'addButtonTitle' => 'ADD_NEW_GATEWAY', // optional
    'searchButtonTitle' => 'SEARCH_GATEWAY', // optional
    'modalCreateHeader' => 'GATEWAY_HEADER_CREATE', // optional
    'modalUpdateHeader' => 'GATEWAY_HEADER_UPDATE', // optional
    'modalSize' => 'large',
    'afterAjaxUpdate' => 'function(){    
            setCreateButtonVisibility();
            subscribeForGatewayEvents();
    }',
    'headerAttribute' => 'name', // TEST
    'itemsCssClass' => 'plTable items',
    'dataProvider' => $model->search(),
    'filter' => $model,
//    'customButtons' => array(
//        'label' => __("GLOBAL_IMPORT_EXPORT_ITEMS"),
//        'icon' => 'wrench',
//        'url' => '',
//        'position' => 'right',
//        "items" => array(
//            array(
//                "label" => __("GLOBAL_CSV_EXPORT"),
//                "url" => url('routingGateways/default/export'),
//                'linkOptions' => array(
//                    'data-translation-id' => 'GLOBAL_CSV_EXPORT'
//                ),
//            ),
//            array(
//                "label" => __("GLOBAL_CSV_IMPORT"),
//                'linkOptions' => array(
//                    'data-translation-id' => 'GLOBAL_CSV_IMPORT'
//                ),
//                "url" => url(
//                        'addressbookImportExport/default/index', array(
//                    'params' => array(
//                        'model' => 'Gateway',
//                        'csvImported' => '1',
//                        'returnUrl' => url('routingGateways/default/index'),
//                    )
//                        )
//                )
//            ),
//        ),
//        'linkOptions' => array(
//            'data-translation-id' => 'GLOBAL_IMPORT_EXPORT_ITEMS'
//        )
//    ),
    'columns' => array(
        array(
            'name' => 'active',
            'type' => 'raw',
            'value' => array($model, 'renderActiveGateway'),
            'header' => __('GATEWAY_MODEL_ACTIVE_ICON'),
            'headerHtmlOptions' => array('data-translation-id' => 'GATEWAY_MODEL_ACTIVE_ICON'),
            'disableSearchField' => true,
        ),
        array(
            'name' => 'state',
            'type' => 'raw',
            'value' => array($model, 'renderState'),
            'header' => $model->getAttributeLabel('state'),
            'headerHtmlOptions' => array('data-translation-target' => 'GATEWAY_MODEL_STATE_TRANSLATIONS'),
            "htmlOptions" => array("class" => "state"),
            'disableSearchField' => true,
        ),
        array(
            'name' => 'name',
            'header' => $model->getAttributeLabel('name'),
            'headerHtmlOptions' => array('data-translation-id' => 'GATEWAY_MODEL_NAME')
        ),
        array(
            'name' => 'providerTemplate',
            'header' => $model->getAttributeLabel('providerTemplate'),
            'headerHtmlOptions' => array('data-translation-id' => 'GATEWAY_MODEL_PROVIDER_TEMPLATE'),
            'value' => array($this, "renderProviderCell")
        ),
        array(
            'name' => 'authname',
            'header' => $model->getAttributeLabel('authname'),
            'headerHtmlOptions' => array('data-translation-id' => 'GATEWAY_MODEL_AUTHNAME')
        ),
        array(
            'class' => 'ext.PlGrid.PlCButtonColumn',
            'template' => '{ajaxUpdate}{delete}',
        )
    ),
        )
);

if (Yii::app()->user->translateMode) {
    echo '<i data-translation-target="GATEWAY_MODEL_STATE_TRANSLATIONS" data-translation-id="GATEWAY_MODEL_STATE"></i>';
    echo '<i data-translation-target="GATEWAY_MODEL_STATE_TRANSLATIONS" data-translation-id="GATEWAY_MODEL_GATEWAY_STATE_REGISTERED"></i>';
    echo '<i data-translation-target="GATEWAY_MODEL_STATE_TRANSLATIONS" data-translation-id="GATEWAY_MODEL_GATEWAY_STATE_UNREGISTERED"></i>';
    echo '<i data-translation-target="GATEWAY_MODEL_STATE_TRANSLATIONS" data-translation-id="GATEWAY_MODEL_GATEWAY_STATE_REGISTER_NEW"></i>';
}
$routingGatewaysMax = PhonalisaLicenseManager::routingGatewayMax();
?>
<script>

    var defaultWsOnMessage = ws.onmessage;
    ws.onmessage = function (e) {
        var msg = jQuery.parseJSON(e.data);
        if (msg.name == "login") {
            subscribeForGatewayEvents();
        } else if (msg.name == "gatewayChanged") {
            setGateWayState(msg.data.gateway);
        }
        defaultWsOnMessage(e);
    };

    var subscribedGateways = [];
    function subscribeForGatewayEvents()
    {
        $("#gateway-grid tbody tr td:first-child").each(function (i, e) {
            
            var gatewayId = $(e).find("span").data("gatewayid");
            
            if (subscribedGateways.indexOf(gatewayId)  === -1) {
                ws.command({
                    type: "command",
                    name: "subscribeGatewayEvents",
                    data: {
                        gateway_id: gatewayId
                    }
                });

                subscribedGateways.push(gatewayId);
            }
        });
        //ws.command({type:"command",name:"subscribeGatewayEvents",data:{gateway_id:gatewayId}})
    }

    function setGateWayState(gateway)
    {
        console.log(gateway.id);
        console.log(gateway.state);
        var stateCell = $("span[data-gatewayid='" + gateway.id + "']").closest("tr").find(".state");
        stateCell.text("");
        var newLabel = $("<span />")
        if (gateway.state === "TRYING") {
            newLabel.addClass("label");
            newLabel.text("<?php echo __("GATEWAY_MODEL_GATEWAY_STATE_REGISTER_NEW") ?>");
        } else if (gateway.state === "NOREG") {
            newLabel.addClass("label");
            newLabel.text("<?php echo __("GATEWAY_MODEL_GATEWAY_STATE_UNREGISTERED") ?>");
        } else if (gateway.state === "REGISTER") {
            newLabel.addClass("label");
            newLabel.text("<?php echo __("GATEWAY_MODEL_GATEWAY_STATE_REGISTER_NEW") ?>");

        } else if (gateway.state === "REGED") {
            newLabel.addClass("label").addClass("label-success");
            newLabel.text("<?php echo __("GATEWAY_MODEL_GATEWAY_STATE_REGISTERED"); ?>");
        } else {
            newLabel.text("n/a");
        }
        stateCell.append(newLabel);
    }

    function setCreateButtonVisibility() {
        if ($("#gateway-grid tbody tr").length >= <?php echo $routingGatewaysMax; ?>
        && !$("#gateway-grid tbody tr td:first-child").hasClass("empty") && <?php echo $routingGatewaysMax; ?> >= 0) {
            $("#gateway-gridCreateBtn").hide();
        } else {
            $("#gateway-gridCreateBtn").show();
        }
    }
    setCreateButtonVisibility();
</script>
