<?php
cs()->registerScriptFile(Yii::app()->baseUrl . '/js/provisioningGeneral/networkScannWSOverwrite.js', CClientScript::POS_END);

$defaultNetworkInterface = "";
$this->widget('ext.PlNavbar', array(
    'brand' => __('NETWORK_SCAN_HEADER_TITLE'),
    'htmlOptions' => array(
        'data-translation-id' => 'NETWORK_SCAN_HEADER_TITLE',
    ),
    'items' => array(
        array(
            'class' => 'bootstrap.widgets.TbMenu',
            'items' => array(
                '---',
                array(
                    'label' => __('GLOBAL_BACK'),
                    'url' => url('provisioningGeneral'),
                    'icon' => 'arrow-left',
                ),
                $this->getNavBarNetworkInterfaceDropdown($defaultNetworkInterface),
                array(
                    'label' => __("PROVISIONING_GENERAL_NAVBAR_START_NETWORK_SCAN"),
                    'url' => url('provisioningGeneral/default/startNetworkScan'),
                    "linkOptions" => array(
                        "id" => "startScanBtn",
                        "data-translation-target" => "PROVISIONING_GENERAL_NAVBAR_START_NETWORK_SCAN"
                    )
                ),
                array(
                    'label' => __("PROVISIONING_GENERAL_NAVBAR_CANCEL_NETWORK_SCAN"),
                    'url' => url('provisioningGeneral/default/cancelNetworkScan'),
                    "linkOptions" => array(
                        "id" => "cancelScanBtn",
                        "style" => "display:none",
                        "data-translation-id" => "PROVISIONING_GENERAL_NAVBAR_CANCEL_NETWORK_SCAN"
                    )
                ),
                array(
                    'label' => __('GLOBAL_SEARCH'),
                    'url' => "#",
                    "linkOptions" => array(
                        "id" => "toggleSearchButton"
                    ),
                    'icon' => 'search',
                ),
            ),
        ),
    ),
));

echo CHtml::hiddenField("networkInterface", $defaultNetworkInterface);

$this->widget(
        'bootstrap.widgets.TbButtonGroup', array(
    'toggle' => 'checkbox',
    'buttons' => array(
        array(
            'label' => __('PROVISIONING_GENERAL_NAVBAR_HIDE_UNSUPPORTED_NETWORK_SCAN_RESULTS'),
            "htmlOptions" => array(
                "id" => "hideUnsupportedBtn",
                "data-translation-id" => "PROVISIONING_GENERAL_NAVBAR_HIDE_UNSUPPORTED_NETWORK_SCAN_RESULTS"
            )
        ),
        array(
            'label' => __("PROVISIONING_GENERAL_NAVBAR_HIDE_KNOWN_DEVICES"),
            "htmlOptions" => array(
                "id" => "hideKnownBtn",
                "data-translation-id" => "PROVISIONING_GENERAL_NAVBAR_HIDE_KNOWN_DEVICES"
            )
        ),
    ),
        )
);

echo "<div id='progressInfo' class='fade'>";
$this->widget('bootstrap.widgets.TbProgress', array(
    'percent' => 0, // the progress
    'striped' => true,
    'animated' => true,
    'htmlOptions' => array(
        'id' => "scanProgressBar",
        'style' => 'margin-bottom:0;'
    )
));
echo "</div>";

$this->widget('ext.PlGrid.PlGridView', array(
    'id' => 'network-scan-result-grid',
    'itemsCssClass' => 'plTable items',
    "navBarHtmlOptions" => array("style" => "display:none"),
    "summaryText" => false,
    'ajaxUpdate' => true,
    'enableHistory' => false,
    'dataProvider' => $model->search(),
    'afterAjaxUpdate' => 'function(id, data){ 

        if (currentFilter & filterNotIsSupported) {
            $("#network-scan-result-grid tbody tr").each(function (i,row) {
                var row = $(row);
                if (!row.hasClass("isSupported")) {
                    row.addClass("hideRow");
                }
            });
        }
        
        if (currentFilter & filterIsKnownDevice) {
            $("#network-scan-result-grid tbody tr").each(function (i,row) {
                var row = $(row);
                if ($(row).hasClass("isKnownDevice")) {
                    row.addClass("hideRow");
                }
            });
        }
    }',
    'filter' => $model,
    'itemsCssClass' => 'plTable items table table-striped table-bordered table-condensed',
    'rowCssClassExpression' => function($row, $data) {
        $cssClass = "";
        if (!isset($data->id)) {
            $cssClass = "hideRow prototype";
        } else {
            if ($data->supported === "true" || $data->supported === true || $data->supported === 1 || $data->supported === "1") {
                $cssClass .= "isSupported";
            }
             if ($data->knownDevice === "true" || $data->knownDevice === true || $data->knownDevice === 1 || $data->knownDevice === "1") {
                $cssClass .= " isKnownDevice";
            }
        }
        return $cssClass;
    },
    'columns' => array(
        array(
            "name" => "created",
            "header" => __("NETWORK_SCAN_MODEL_CREATED"),
            "headerHtmlOptions" => array("data-translation-id" => "NETWORK_SCAN_MODEL_CREATED"),
            "htmlOptions" => array("class" => "created")
        ),
        array(
            "name" => "mac",
            "header" => __("NETWORK_SCAN_MODEL_MAC"),
            "headerHtmlOptions" => array("data-translation-id" => "NETWORK_SCAN_MODEL_MAC"),
            "htmlOptions" => array("class" => "mac")
        ),
        array(
            "name" => "ipv4",
            "header" => __("NETWORK_SCAN_MODEL_IPV4"),
            "headerHtmlOptions" => array("data-translation-id" => "NETWORK_SCAN_MODEL_IPV4"),
            "htmlOptions" => array("class" => "ipv4")
        ),
        array(
            "name" => "vendor",
            "header" => __("NETWORK_SCAN_MODEL_VENDOR"),
            "headerHtmlOptions" => array("data-translation-id" => "NETWORK_SCAN_MODEL_VENDOR"),
            "htmlOptions" => array("class" => "vendor")
        ),
        array(
            'class' => 'bootstrap.widgets.TbButtonColumn',
            'htmlOptions' => array(
                'class' => 'buttonColumnIcons',
                'style' => 'width:55px;cursor: pointer;',
                'data-translation-id' => "GRID_DELETE_TOOLTIP"
            ),
            'template' => '{addToprovisioning}',
            'buttons' => array(
                'addToprovisioning' => array(
                    'label' => '<i class="icon-medkit"></i>',
                    'imageUrl' => false,
                    "visible" => '($data->supported === "true" || $data->supported === true || $data->supported === 1 || $data->supported === "1")',
                    'options' => array(
                        'title' => __('INITIATE_PROVISIONING'),
                        'data-translation-id' => 'INITIATE_PROVISIONING',
                    ),
                    'url' => 'Yii::app()->createUrl("provisioningGeneral/default/addToProvisioning", array("id"=>"$data->id"))',
                    'click' => 'js:function(){
                                $.get(this.href, function(data){
                                    return false;
                                });
                            return false;
                            }',
                ),
            )
        )
    ),
));

if (app()->user->translateMode) {
    echo "<i data-translation-target ='PROVISIONING_GENERAL_NAVBAR_START_NETWORK_SCAN' data-translation-id='PROVISIONING_GENERAL_NAVBAR_START_NETWORK_SCAN'></i>";
    echo "<i data-translation-target ='PROVISIONING_GENERAL_NAVBAR_START_NETWORK_SCAN' data-translation-id='NETWORK_SCAN_IN_PROGRESS'></i>";
    echo "<i data-translation-target ='PROVISIONING_GENERAL_NAVBAR_START_NETWORK_SCAN' data-translation-id='PROVISIONING_GENERAL_NAVBAR_CANCEL_NETWORK_SCAN'></i>";
}
?>
<style>
    .hideRow {
        display:none;
    }
    #progressInfo {
        margin-top: 15px;
    }

    .searchInProgressImg{
        padding-left: 10px;
    }

</style>
<script>

    initProgressBar();

    function initProgressBar()
    {

        var currentJob = <?php echo $networkScannJobJSON; ?>;
        if (typeof currentJob.type !== "undefined") {
            onJobChangedEvent(currentJob);
        }
    }
    // filter Flags
    var filterNotIsSupported = 1;
    var filterIsKnownDevice = 2;

    var currentFilter = 0;

    $("#startScanBtn, #hideUnsupportedBtn, #hideKnownBtn, #toggleSearchButton").on("click", function () {
        document.activeElement.blur();
    });

    $('#startScanBtn').on("click", function () {

        $.ajax({
            type: "POST",
            url: $(this).attr("href"),
            data: {
                networkInterfaceIp: $("#networkInterface").val()
            },
            success: function () {
                $.fn.yiiGridView.update("network-scan-result-grid");
            }
        });
        $('#cancelScanBtn').show();
        $(this).text("<?php echo __("NETWORK_SCAN_IN_PROGRESS") ?>");
        setProgress(0);
        return false;
    });

    $('#cancelScanBtn').on("click", function () {
        $.ajax({
            type: "POST",
            url: $(this).attr("href"),
            data: {
                networkInterfaceIp: $("#networkInterface").val()
            }
        });
        $(this).hide();
        $.fn.yiiGridView.update("network-scan-result-grid");
        resetProgressBar();
        $('#startScanBtn').text("<?php echo __("PROVISIONING_GENERAL_NAVBAR_START_NETWORK_SCAN"); ?>");
        return false;
    });

    $(".networkInterfaceValue").click(function () {
        $("#networkInterface").val($(this).data("value"));
        $(this).parents(".dropdown").find(" >a").text($(this).text()).append($("<span />").addClass("caret"));
    });

    $("#hideUnsupportedBtn").on("click", function ()
    {
        if ($(this).parent().hasClass("active")) {
            $(this).parent().removeClass("active");

            currentFilter = (currentFilter - filterNotIsSupported);
        } else {
            $(this).parent().addClass("active");
            currentFilter = (currentFilter + filterNotIsSupported);
        }
        setAllRowVisibility();
    });

    $("#hideKnownBtn").on("click", function () {

        if ($(this).parent().hasClass("active")) {
            $(this).parent().removeClass("active");
            currentFilter = (currentFilter - filterIsKnownDevice);
        } else {
            $(this).parent().addClass("active");
            currentFilter = (currentFilter + filterIsKnownDevice);
        }
        setAllRowVisibility();
    });

    $('#toggleSearchButton').on("click", function () {
        $(this).parent().toggleClass("active");
        $("#content").find('.activeGrid').toggleClass("search");
    });

    function setAllRowVisibility()
    {
        $('#network-scan-result-grid tbody tr').each(function (i, row) {
            setRowVisibility(row);
        });
    }

    function setRowVisibility(row) {
        var showRow = true;
        var row = $(row);

        if ((currentFilter & filterNotIsSupported) && !row.hasClass("isSupported")) {
            showRow = false;
        }

        if ((currentFilter & filterIsKnownDevice) && row.hasClass("isKnownDevice")) {
            showRow = false;
        }
        if (showRow === true && !row.hasClass("prototype")) {
            row.removeClass("hideRow");
        } else {
            row.addClass("hideRow");
        }
    }

    function onJobChangedEvent(job)
    {
        if (parseInt(job.type) === <?php echo Job::NetworkScan; ?>)
        {
            $('#cancelScanBtn').show();
            $('#startScanBtn').text("<?php echo __("NETWORK_SCAN_IN_PROGRESS"); ?>");
            var img = $("<img />")
                    .attr("class", "searchInProgressImg")
                    .attr('src', '/img/loading.gif');
            $('#startScanBtn').parent().find("a").append(img);

            fadeInProgressBar();
            disableSortLinks();
            disableSearch();
            updateProgressBar(job.progress);
        } else if (parseInt(job.type) === <?php echo Job::AddPhoneToProvisioning; ?>) {
            updateProvisioningInitiatorStatus(job);
        }
    }

    function fadeInProgressBar()
    {
        if (!$("#progressInfo").hasClass("in")) {
            $("#progressInfo")
                    .addClass("alert")
                    .addClass("alert-info")
                    .addClass("out")
                    .addClass("fade")
                    .show();
        }
        setTimeout(function () {
            $("#progressInfo").addClass("in").removeClass("out");
        }, 200);
    }

    function disableSortLinks()
    {
        $("#network-scan-result-grid thead th").each(function (i, cell) {
            if ($(cell).find("a").length > 0) {
                $(cell).text($(cell).find("a").text());
            }
        });
    }

    function disableSearch() {
        $("#toggleSearchButton").hide();
        $("#toggleSearchButton").parent().removeClass("active");
        $("#content").find('.activeGrid').removeClass("search");
    }

    function updateProgressBar(progress)
    {
        if (typeof progress === "undefined") {
            progress = 0;
        }
        setProgress(progress);

        if (progress >= 100) {
            setTimeout(function () {
                resetProgressBar();
                $('#startScanBtn').text("<?php echo __("PROVISIONING_GENERAL_NAVBAR_START_NETWORK_SCAN"); ?>");
            }, 1000);
        }
    }

    function resetProgressBar()
    {
        fadeOutProgressBar();
        setTimeout(function () {
            setProgress(0);
        }, 300);
        $('#cancelScanBtn').hide();
        enableSortLinks();
        enableSearch();
    }

    function fadeOutProgressBar()
    {
        $("#progressInfo").removeClass("in").addClass("out");
        setTimeout(function () {
            $("#progressInfo").hide();
        }, 200);
    }

    function setProgress(progress)
    {
        $("#scanProgressBar .bar").width(progress + "%");
        $("#scanProgressBar > div").text(progress + "%");
    }

    function enableSortLinks()
    {
        var attributes = [
            "<?php echo __("NETWORK_SCAN_MODEL_CREATED"); ?>",
            "<?php echo __("NETWORK_SCAN_MODEL_MAC"); ?>",
            "<?php echo __("NETWORK_SCAN_MODEL_IPV4"); ?>",
            "<?php echo __("NETWORK_SCAN_MODEL_VENDOR"); ?>"
        ];
        $("#network-scan-result-grid thead th").each(function (i, cell) {
            $(cell).text("");
            var sortLink = $("<a />");
            sortLink.addClass("sort-link");
            sortLink.attr("href", "/index.php?r=provisioningGeneral/default/networkScan&amp;sort=" + attributes[i]);
            sortLink.text(attributes[i]);
            var caret = $("<span />").addClass("caret");

            sortLink.append(caret);
            $(cell).append(sortLink);
        });
    }

    function enableSearch()
    {
        $("#toggleSearchButton").show();
    }

    function updateProvisioningInitiatorStatus(job)
    {
        var buttonCell = $("[href*='" + job.meta + "']").parent();
        if (job.status === <?php echo Job::Running; ?> && buttonCell.find("img").length === 0) { // JobStatusRunning
            buttonCell.find("a").remove();
            buttonCell.find('.tooltip').hide();
            buttonCell.append("<img src='../img/loading.gif' href='#?" + job.meta + "'/>");
        } else if (job.status === <?php echo Job::Finished; ?>) { // JobStatusFinnished
            buttonCell.find("img").remove();
            buttonCell.append("<i class='icon-check'/>"); // FIXME : find better icon ? 
        } else if (job.status === <?php echo Job::Failed; ?>) { // JobStatusFailed
            buttonCell.find("img").remove();
            buttonCell.find('.tooltip-inner').text(job.errorText);
            buttonCell.append("<i class='icon-remove'/>");
        }
    }
    //FIXME fade effect from tooltip
    $("#network-scan-result-grid").on("mouseover", ".icon-remove", function () {
        $(this).closest("td").find(".tooltip").show();
    });
    //FIXME fade effect from tooltip
    $("#network-scan-result-grid").on("mouseleave", ".icon-remove", function () {
        $(this).closest("td").find(".tooltip").hide();
    });

    function onNetworkScanResultChanged(networkScanResult)
    {
        var row = getDisplayedRow(networkScanResult.mac);
        if (row.length === 0) {
            row = getRowPrototype();
            appendNewItem(row);
        }
        fillPrototypeWithData(row, networkScanResult);
        setRowVisibility(row);
    }

    function getDisplayedRow(mac)
    {
        return $("td").filter(function () {
            return $.text([this]) == mac;
        }).closest("tr");
    }

    function getRowPrototype()
    {
        var prototype = $('#network-scan-result-grid tbody tr:first-child').clone();
        if (!prototype.find(".icon-medkit").length) {
            addButtonIcons(prototype);
        }
        return prototype;
    }

    function addButtonIcons(prototype)
    {
        var addToProvisioningButtonLink = $("<a />");
        addToProvisioningButtonLink.attr("data-translation-id", "INITIATE_PROVISIONING");
        addToProvisioningButtonLink.addClass("addToprovisioning");
        addToProvisioningButtonLink.attr("rel", "tooltip");
        addToProvisioningButtonLink.attr("title", "<?php echo __("INITIATE_PROVISIONING") ?>");

        addToProvisioningButtonLink.attr("href", "/index.php?r=provisioningGeneral/default/addToProvisioning&id=");
        var addToProvisioningButtonIcon = $("<i />").addClass("icon-medkit");
        addToProvisioningButtonLink.append(addToProvisioningButtonIcon);
        prototype.find(".buttonColumnIcons").append(addToProvisioningButtonLink);
    }

    function fillPrototypeWithData(prototypeRow, networkScanResult)
    {
        $.each(networkScanResult, function (key, value) {
            prototypeRow.find("." + key).text(value);
        });
        if (networkScanResult.supported === "true" || networkScanResult.supported === true || networkScanResult.supported === 1 || networkScanResult.supported === "1") {
            prototypeRow.addClass("isSupported");
            var addToProvisioningUrl = getAddToProvisioningUrlFromPrototype(prototypeRow);
            prototypeRow.find(".addToprovisioning").attr("href", addToProvisioningUrl + "&id=" + networkScanResult.id);
        } else {
            prototypeRow.find(".addToprovisioning").remove();
        }

        if (networkScanResult.knownDevice === "true" || networkScanResult.knownDevice === true || networkScanResult.knownDevice === 1 || networkScanResult.knownDevice === "1") {
            prototypeRow.addClass("isKnownDevice");
        }

        prototypeRow.removeClass("prototype");
        prototypeRow.removeClass("hideRow");
    }

    function getAddToProvisioningUrlFromPrototype(prototypeRow)
    {
        var addToProvisioningUrl = prototypeRow.find(".addToprovisioning").attr("href");
        addToProvisioningUrl = addToProvisioningUrl.substring(0, addToProvisioningUrl.indexOf("&id="));
        return addToProvisioningUrl;
    }

    function appendNewItem(newItem)
    {
        $('#network-scan-result-grid tbody').append(newItem);
    }
</script>