@model  PantheonRA.BackOffice.Models.DeviceSettingsViewModel

<div class="row">
    <div class="col-xs-12">
        <div class="flat well">
            <h2 class="m-b-none m-t-none">@Loc.DeviceSettings</h2>
        </div>
    </div>
</div>
<div class="row m-t-md">
    @Html.HiddenFor(model => model.DeviceId)
    <div class="col-md-12">
        <table id="settingsGrid" data-grid-id="device-settings" data-url="@Url.Action("_GetDeviceSettings", "Devices")" class="list-table">
            <thead>
                <tr>
                    <th>@Loc.Name</th>
                    <th>@Loc.Value</th>
                    <th data-column-id="commands" data-sortable="false" data-align="center" data-width="10%">@Loc.Edit</th>
                </tr>
            </thead>
        </table>
    </div>
</div>

<script type="text/javascript" src="~/Scripts/plugins/sweetAlert/sweetalert2.min.js"></script>
<script type="text/javascript">
    $dataTable = $('#settingsGrid');
    $dataTable.DataTable({
        ajax: {
            url: $dataTable.attr('data-url'),
            data: function (d) {
                d.DeviceId = $("#DeviceId").val();
            }
        },
        columns: [
            { data: "DisplayName", name: "DisplayName" },
            { data: "Value", name: "Value" },
            {
                data: null,
                render: function (data, type, row) {
                    return '<button class="btn btn-default btn-outline">@Loc.Edit</button>';
                }
            },
        ]
    });

    $('#settingsGrid tbody').on('click', 'button', function () {
        var data = $dataTable.DataTable().row($(this).parents('tr')).data();

        swal({
            type: 'info',
            title: "@Loc.Edit " + data.DisplayName,
            input: 'textarea',
            inputValue: data.Value,
            inputPlaceholder: '',
            showCancelButton: true,
            confirmButtonText: "@Loc.Save",
        }).then(function (result) {
            if (result.value)
                $.post("@Url.Action("_ChangeDeviceSettings", "Devices")", { deviceId: $("#DeviceId").val(), settingName: data.Name, value: (result.value) ? result.value : "" }, function (data) {
                    if (data.result) {
                        toastr.success("@Loc.SettingsSuccessfullyUpdated!", "@Loc.Success", { timeOut: 2000, closeButton: true });
                        $.fn.dataTable.reload($dataTable);
                    }
                    else {
                        toastr.error("@Loc.ErrorWhileSavingSettings!", "@Loc.Error", { timeOut: 5000, closeButton: true });
                    }
                });
        });
    });

    function searchArray(value, array) {
        for (var i = 0; i < array.length; i++) {
            if (array[i].Name === value) {
                return array[i];
            }
        }
    }
</script>
