@model PantheonRA.BackOffice.Models.DeviceProductSynchronizationSettingsViewModel
@{
    ViewBag.Title = Loc.DeviceSyncSettings;
}


<div class="row wrapper border-bottom white-bg page-heading">
    <div class="col-lg-10">
        <a class="navbar-minimalize btn btn-primary " href="#"><i class="fa fa-bars"></i> </a>
        <h2>@ViewBag.Title</h2>
        <span class="breadcrumb-divider">&bull;</span>
        <ol class="breadcrumb">
            <li><a href="@Url.Action("Index", "DeviceSynchronizationSettings")">Home</a></li>
            <li>@Loc.AdministrationPanel</li>
            <li class="active"><strong>@ViewBag.Title</strong></li>
        </ol>
    </div>
    <div class="col-lg-2">
    </div>
</div>


<div class="wrapper wrapper-content animated fadeIn fiscal-certificate-wrapper">
    <div class="row">
        <div class="col-xs-12">
            <div class="pull-right">
                <button id="btnSaveSyncSettings" type="button" class="btn btn-primary m-b-xs">
                    <div class="text-center" id="spinnerUpdateSyncSettings" style="display: none;">
                        <div class="sk-spinner sk-spinner-three-bounce">
                            <div class="sk-bounce1"></div>
                            <div class="sk-bounce1"></div>
                            <div class="sk-bounce2"></div>
                        </div>
                    </div>
                    <span>@Loc.Save</span>
                </button>
            </div>
            <div class="clearfix"></div>
        </div>

        <div class="col-xs-6">
            <div class="ibox">
                <div class="ibox-title">
                    <h5>@Loc.AllProducts</h5>
                </div>
                <div class="ibox-content">
                    <div class="row m-b-sm m-t-sm">
                        <div class="col-md-12">
                            <div class="row">
                                <div class="col-md-10">
                                    <div class="form-group">
                                        <input type="text" placeholder="@Loc.SearchProducts..." id="ProductsFilterKeywords" class="form-control" />
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <button type="button" id="searchAllProductsGrid" class="btn btn-block btn-outline btn-primary">@Loc.Search</button>
                                    </div>
                                </div>
                            </div>

                        </div>
                    </div>

                    <div class="project-list">
                        <table id="allProductsGrid" class="list-table">
                            <thead>
                                <tr>
                                    <th data-column-id="Id" data-type="numeric" data-visible="false" data-identifier="true">Id</th>
                                    <th data-column-id="Name">@Loc.Name</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xs-6">
            <div class="ibox">
                <div class="ibox-title">
                    <h5>@Loc.ProductsSelectedForSynchronization</h5>
                </div>
                <div class="ibox-content">
                    <div class="selected-sync-products-count"><span>@Loc.ProductsSelected: </span><span id="productsInSyncCounter" class="selected-count">@Model.ProductsInSync.Count()</span><span>/@Model.MaxNumberOfProductsInSync</span></div>
                    <div class="project-list">
                        <table id="productsInSyncGrid" class="list-table">
                            <thead>
                                <tr>
                                    <th data-column-id="Id" data-type="numeric" data-visible="false" data-identifier="true">Id</th>
                                    <th data-column-id="Name">@Loc.Name</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach (var productInSync in Model.ProductsInSync)
                                {
                                    <tr>
                                        <td>@productInSync.Id</td>
                                        <td>@productInSync.Name</td>
                                    </tr>
                                }
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


@section pageCss{
    <link href="~/Content/jquery.bootgrid.css" rel="stylesheet" />
}

@section pageScripts{
    <script type="text/javascript" src="~/Scripts/jquery.bootgrid.min.js"></script>

    <script type="text/javascript">

        var selectedProductIds = @Html.SerializeObjectToJavascriptObjectNotation(Model.ProductsInSync.Select(p => p.Id));
        var productsInSyncCounter = @Model.ProductsInSync.Count();
        var maxProductsInSync = @Model.MaxNumberOfProductsInSync;

        var productsInSyncGrid = $("#productsInSyncGrid").bootgrid({
            templates: {
                search: "",
                header: "",
                pagination: ""
            },
            labels: {
                noResults: "@Loc.NoResultFound",
                infos: "@Loc.Showing {{ctx.total}}",
                loading: "@Loc.Loading..."
            },
            ajax: false,
            rowCount: -1
        });

        var allProductsGrid = $("#allProductsGrid").bootgrid({
            ajax: true,
            url: "@Url.Action("_GetDeviceSnychronizationCategories", "DeviceSynchronizationSettings")",
            selection: true,
            multiSelect: true,
            keepSelection: true,
            templates: {
                search: "",
                header: ""
            },
            labels: {
                noResults: "@Loc.NoResultFound",
                infos: "@Loc.Showing {{ctx.start}} @Loc.To.ToLower() {{ctx.end}} ({{ctx.total}})",
                loading: "@Loc.Loading..."

            },
            post: function () {
                return {
                    Keywords: $("#ProductsFilterKeywords").val()
                };
            },
        }).on("selected.rs.jquery.bootgrid", function (e, rows) {
            if (rows.length > 0) {

                var rowIdsToDeselect = [];
                var maxLimitReached = false;

                for(var rowCounter = 0; rowCounter < rows.length; rowCounter++)
                {
                    var index = selectedProductIds.indexOf(rows[rowCounter].Id);

                    if (index === -1) {
                        if(productsInSyncCounter >= maxProductsInSync)
                        {
                            if(!maxLimitReached)
                            {
                                toastr.warning("@Loc.MaximumNumberOfProductsInSyncIs" + " " + maxProductsInSync + ".", "@Loc.Warning", { timeOut: 5000, closeButton: true });
                                maxLimitReached = true;
                            }
                            rowIdsToDeselect.push(rows[rowCounter].Id);
                        }
                        else
                        {
                            productsInSyncCounter++;
                            $("#productsInSyncCounter").html(productsInSyncCounter);
                            selectedProductIds.push(rows[rowCounter].Id);
                            AddProductToTheInSyncGrid(rows[rowCounter].Id, rows[rowCounter].Name);
                        }
                    }

                    if(maxLimitReached)
                    {
                        $("#allProductsGrid").bootgrid('deselect', rowIdsToDeselect);
                    }
                }
            }
        }).on("deselected.rs.jquery.bootgrid", function (e, rows) {
            if (rows.length > 0) {
                for(var rowCounter = 0; rowCounter < rows.length; rowCounter++)
                {
                    var index = selectedProductIds.indexOf(rows[rowCounter].Id);
                    if (index > -1) {
                        productsInSyncCounter--;
                        $("#productsInSyncCounter").html(productsInSyncCounter);
                        selectedProductIds.splice(index, 1);
                        RemoveProductFromTheInSyncGrid(rows[rowCounter].Id);
                    }
                }
            }
        }).on("loaded.rs.jquery.bootgrid", function (e) {
            if(selectedProductIds[0] !== undefined)
            {
                var selectedRows = $("#allProductsGrid").bootgrid("getSelectedRows");
                var rowIds = selectedProductIds.filter(function(n){ return selectedRows.indexOf(n) == -1 });

                $("#allProductsGrid").bootgrid("select", rowIds);
            }
        });

        $("#searchAllProductsGrid").on("click", function () {
            allProductsGrid.bootgrid('reload');
        });

        function AddProductToTheInSyncGrid(productId, productName)
        {
            var rowsToAdd = [{ "Name": productName, "Id": productId, "IsSelected": false, "SyncStatus": "" }];
            $("#productsInSyncGrid").bootgrid('append', rowsToAdd);
        }

        function RemoveProductFromTheInSyncGrid(productId)
        {
            var rowsToRemove = [productId];
            $("#productsInSyncGrid").bootgrid('remove', rowsToRemove);
        }

        $("#btnSaveSyncSettings").on("click", function(){
                var buttonClicked = this;
                buttonClicked.disabled = true;
                $("#spinnerUpdateSyncSettings").show();
                $("#btnSaveSyncSettings").addClass("btn-outline");
                $("#btnSaveSyncSettings span").hide();

                $.ajax({
                    method: "POST",
                    url: "@Url.Action("SaveDeviceProductSyncSettings", "DeviceSynchronizationSettings")",
                    data: { productIdsInSync: selectedProductIds },
                    success: function (isUpdateSuccess) {
                        if(isUpdateSuccess)
                        {
                            toastr.success("@Loc.DeviceSynchronizationSettingsUpdated!", "@Loc.Success", { timeOut: 2000, closeButton: true });
                        }
                        else
                        {
                            toastr.error("@Loc.MaximumNumberOfProductsInSyncIs" + " " + maxProductsInSync + ".", "@Loc.Error", { timeOut: 5000, closeButton: true });
                        }
                    },
                    error: function () {
                        toastr.error("@Loc.ErrorHappenedPleaseContactOurSupport", "@Loc.Error", { timeOut: 5000, closeButton: true });
                    },
                    complete: function(){
                        buttonClicked.disabled = false;
                        $("#spinnerUpdateSyncSettings").hide();
                        $("#btnSaveSyncSettings").removeClass("btn-outline");
                        $("#btnSaveSyncSettings span").show();
                    }
            });
        });

    </script>
}