@model  PantheonRA.BackOffice.Models.DeviceSynchronizationSettingsViewModel

<div class="row">
    <div class="col-xs-12">
        <h2>@Loc.DeviceSynchronizationSettings</h2>
    </div>
</div>
<div class="row">
    <div class="col-xs-12">
        <div class="form-group pull-left sync-enabled-cbx">
            @*@Html.LabelFor(model => model.PremiseType, "Premise type?")
                @Html.TextBoxFor(model => model.PremiseType, new { @id = "PremiseType", @class = "form-control", @placeholder = "Premise type?..." })
                @Html.ValidationMessageFor(model => model.PremiseType)*@
            <div class="form-group no-label-control">
                <div>
                    @Html.CheckBoxFor(model => model.IsDeviceSynchronizationEnabled, new { @id = "IsDeviceSynchronizationEnabled", @class = "form-control js-switch" })
                    @Html.LabelFor(model => model.IsDeviceSynchronizationEnabled, Loc.DoYouWishToSynchronizeSpecificProductsAndCategoryToDevice)
                </div>
            </div>
        </div>
        <div class="pull-right">
            <button id="btnSaveDeviceSyncSettings" type="button" class="btn btn-primary save-sync-settings-btn">
                <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.SaveDeviceSynchronizationSettings</span>
            </button>
        </div>
        <div class="clearfix"></div>
        <div class="hr-line-dashed"></div>
    </div>
    <div class="col-lg-6 device-sync-settings-grids">
        <div class="gridsOverlay"></div>
        <div class="row">
            <div class="col-xs-12">
                <span id="productsCounter" class="selected-count">@Model.SelectedProductIds.Count()</span><span class="text-small-muted">@Loc.SelectedProducts</span>
                &bull;
                <button id="btnSelectAllProducts" type="button" class="btn btn-xs btn-link btn-select-link m-xs">@Loc.SelectAllProducts</button>
                <button id="btnDeselectAllProducts" type="button" class="btn btn-xs btn-link btn-select-link m-xs">@Loc.DeselectAllProducts</button>
            </div>
            <div class="col-xs-10">
                <div class="subGridsProductsOverlay"></div>
                <div class="form-group">
                    @Html.TextBoxFor(model => model.ProductKeywords, new { @id = "searchProductsKeywords", @class = "form-control", @placeholder = @Loc.SearchByName + "..." })
                </div>
            </div>
            <div class="col-xs-2">
                <div class="subGridsProductsOverlay"></div>
                <div class="form-group">
                    <button type="button" id="searchProductsGrid" class="btn btn-block btn-outline btn-primary">@Loc.Search</button>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="subGridsProductsOverlay"></div>
                <table id="productsGrid" 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="Code">@Loc.Code</th>
                            <th data-column-id="Name" data-formatter="DeviceNumber">@Loc.Name</th>
                        </tr>
                    </thead>
                </table>
            </div>
        </div>
    </div>
    <div class="col-lg-6 device-sync-settings-grids">
        <div class="gridsOverlay"></div>
        <div class="row">
            <div class="col-xs-12">
                <span id="categoriesCounter" class="selected-count">@Model.SelectedCategoryIds.Count()</span><span class="text-small-muted m-r-xs">@Loc.SelectedCategories</span>
                &bull;
                <button id="btnSelectAllCategories" type="button" class="btn btn-xs btn-link btn-select-link m-xs">@Loc.SelectAllCategories</button>
                <button id="btnDeselectAllCategories" type="button" class="btn btn-xs btn-link btn-select-link m-xs">@Loc.DeselectAllCategories</button>
            </div>
            <div class="col-xs-10">
                <div class="subGridsCategoriesOverlay"></div>
                <div class="form-group">
                    @Html.TextBoxFor(model => model.CategoryKeywords, new { @id = "searchCategoriesKeywords", @class = "form-control", @placeholder = @Loc.SearchByName + "..." })
                </div>
            </div>
            <div class="col-xs-2">
                <div class="subGridsCategoriesOverlay"></div>
                <div class="form-group">
                    <button type="button" id="searchCategoriesGrid" class="btn btn-block btn-outline btn-primary">@Loc.Search</button>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="subGridsCategoriesOverlay"></div>
                <table id="categoriesGrid" 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>

<script type="text/javascript">
    var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
    elems.forEach(function (html) {
        var switchery = new Switchery(html);
    });

    var currentProductsCounter = @Model.SelectedProductIds.Count();
    var currentCategoriesCounter = @Model.SelectedCategoryIds.Count();
    var selectedProductIds = @Html.SerializeObjectToJavascriptObjectNotation(Model.SelectedProductIds);
    var selectedCategoryIds = @Html.SerializeObjectToJavascriptObjectNotation(Model.SelectedCategoryIds);
    
    //alert("Product ids: " + selectedProductIds.join(","));

    var productsGrid = $("#productsGrid").bootgrid({
        ajax: true,
        url: "@Url.Action("_GetDeviceSnychronizationProducts", "Devices")",
        selection: true,
        multiSelect: 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: $("#searchProductsKeywords").val()
            };
        },
    }).on("selected.rs.jquery.bootgrid", function (e, rows) {
        if(rows.length == 1){
            var index = selectedProductIds.indexOf(rows[0].Id);
            if(index === -1){
                currentProductsCounter++;
                $("#productsCounter").html(currentProductsCounter);
                selectedProductIds.push(rows[0].Id);
            }
            //alert("Product added: " + selectedProductIds.join(",") + " || " + $("#productsGrid").bootgrid("getSelectedRows").join(","));
        }
    }).on("deselected.rs.jquery.bootgrid", function (e, rows) {
        if(rows.length == 1) {
            var index = selectedProductIds.indexOf(rows[0].Id);
            if(index > -1)
            {
                currentProductsCounter--;
                $("#productsCounter").html(currentProductsCounter);
                selectedProductIds.splice(index, 1);
                //alert("Product removed: " + selectedProductIds.join(",") + " || " + $("#productsGrid").bootgrid("getSelectedRows").join(","));
            }
        }
    }).on("loaded.rs.jquery.bootgrid", function (e)
    {
        //alert("Grid before loaded: " + selectedProductIds.join(",") + " || " + $("#productsGrid").bootgrid("getSelectedRows").join(","));
        if(selectedProductIds[0] !== undefined)
        {
            var selectedRows = $("#productsGrid").bootgrid("getSelectedRows");
            var rowsToSelect = selectedProductIds.filter(function(n){ return selectedRows.indexOf(n) == -1 });
            $("#productsGrid").bootgrid("select", rowsToSelect);
            //alert("Grid loaded: " + selectedProductIds.join(",") + " || " + $("#productsGrid").bootgrid("getSelectedRows").join(","));
        }
    });
    
    $("#searchProductsGrid").on("click", function () {
        $("#productsGrid").bootgrid('reload');
    });

    var categoriesGrid = $("#categoriesGrid").bootgrid({
        ajax: true,
        url: "@Url.Action("_GetDeviceSnychronizationCategories", "Devices")",
        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: $("#searchCategoriesKeywords").val()
            };
        },
    }).on("selected.rs.jquery.bootgrid", function (e, rows) {
        if(rows.length == 1){
            var index = selectedCategoryIds.indexOf(rows[0].Id);
            if(index === -1)
            {
                currentCategoriesCounter++;
                $("#categoriesCounter").html(currentCategoriesCounter);
                selectedCategoryIds.push(rows[0].Id);
            }
        }
    }).on("deselected.rs.jquery.bootgrid", function (e, rows) {
        if(rows.length == 1) {
            var index = selectedCategoryIds.indexOf(rows[0].Id);
            if(index > -1)
            {
                currentCategoriesCounter--;
                $("#categoriesCounter").html(currentCategoriesCounter);
                selectedCategoryIds.splice(index, 1);
            }
        }
    }).on("loaded.rs.jquery.bootgrid", function (e)
    {
        if(selectedCategoryIds[0] !== undefined)
        {
            var selectedRows = $("#categoriesGrid").bootgrid("getSelectedRows");
            var rowsToSelect = selectedCategoryIds.filter(function(n){ return selectedRows.indexOf(n) == -1 });
            $("#categoriesGrid").bootgrid("select", rowsToSelect);
        }
    });
    
    $("#searchCategoriesGrid").on("click", function () {
        categoriesGrid.bootgrid('reload');
    });

    var isDeviceSyncEnabledCbx = document.querySelector('#IsDeviceSynchronizationEnabled');
    DisableDiv(!isDeviceSyncEnabledCbx.checked, ".gridsOverlay");
    isDeviceSyncEnabledCbx.onchange = function(){ DisableDiv(!isDeviceSyncEnabledCbx.checked, ".gridsOverlay"); };

    function DisableDiv(isDisabled, divIdentifier)
    {
        if (isDisabled) {
            $(divIdentifier).addClass("disabled-div");
        }
        else {
            $(divIdentifier).removeClass("disabled-div");
        }
    }
    function HandleCounterDisplay(isAllSelected, counterIdentifier, counter)
    {
        if(isAllSelected)
        {
            $(counterIdentifier).html("@Loc.All");
        }
        else
        {
            $(counterIdentifier).html(counter);
        }
    }

    var areAllProductsSelected = false;
    var areAllCategoriesSelected = false;
    $("#btnSelectAllProducts").on("click", function(){
        areAllProductsSelected = !areAllProductsSelected;
        if(areAllProductsSelected)
        {
            DisableDiv(true, ".subGridsProductsOverlay");
            HandleCounterDisplay(true, "#productsCounter", currentProductsCounter);
            $(this).addClass("text-primary");
        }
        else
        {
            DisableDiv(false, ".subGridsProductsOverlay");
            HandleCounterDisplay(false, "#productsCounter", currentProductsCounter);
            $(this).removeClass("text-primary");
        }
    });
    $("#btnDeselectAllProducts").on("click", function(){
        $("#productsGrid").bootgrid("deselect");
        DisableDiv(false, ".subGridsProductsOverlay");
        currentProductsCounter = 0;
        HandleCounterDisplay(false, "#productsCounter", currentProductsCounter);
        areAllProductsSelected = false;
        selectedProductIds = [];
    });

    $("#btnSelectAllCategories").on("click", function(){
        areAllCategoriesSelected = !areAllCategoriesSelected;
        if(areAllCategoriesSelected)
        {
            DisableDiv(true, ".subGridsCategoriesOverlay");
            HandleCounterDisplay(true, "#categoriesCounter", currentCategoriesCounter);
            $(this).addClass("text-primary");
        }
        else
        {
            DisableDiv(false, ".subGridsCategoriesOverlay");
            HandleCounterDisplay(false, "#categoriesCounter", currentCategoriesCounter);
            $(this).removeClass("text-primary");
        }
    });
    $("#btnDeselectAllCategories").on("click", function(){
        categoriesGrid.bootgrid("deselect");
        DisableDiv(false, ".subGridsCategoriesOverlay");
        currentCategoriesCounter = 0;
        HandleCounterDisplay(false, "#categoriesCounter", currentCategoriesCounter);
        areAllCategoriesSelected = false;
        selectedCategoryIds = [];
    });



    //int deviceId, bool isEnabled, bool areAllCategoriesSelected, IEnumerable<int> selectedCategoryIds, bool areAllProductsSelected, IEnumerable<int> selectedProductIds
   $("#btnSaveDeviceSyncSettings").on("click", function(){
        var buttonClicked = this;
        buttonClicked.disabled = true;
        $("#spinnerUpdateSyncSettings").show();
        $("#btnSaveDeviceSyncSettings").addClass("btn-outline");
        $("#btnSaveDeviceSyncSettings span").hide();

        $.ajax({
            method: "POST",
            url: "@Url.Action("_SaveSynchronizationSettings", "Devices")",
            data: { deviceId: @Model.DeviceId, isEnabled: isDeviceSyncEnabledCbx.checked, areAllCategoriesSelected: areAllCategoriesSelected, selectedCategoryIds: selectedCategoryIds, areAllProductsSelected: areAllProductsSelected, selectedProductIds: selectedProductIds },
            success: function (isUpdateSuccess) {
                if(isUpdateSuccess)
                {
                    toastr.success("@Loc.DeviceSynchronizationSettingsUpdated!", "@Loc.Success", { timeOut: 2000, closeButton: true });
                }
                else
                {
                    toastr.error("@Loc.ErrorHappenedWhileUpdatingTheDeviceSynchronizationSettins.", "@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();
                $("#btnSaveDeviceSyncSettings").removeClass("btn-outline");
                $("#btnSaveDeviceSyncSettings span").show();
            }
        });
    });
</script>