<script src="/js/plugins/tabledit/tabledit.js"></script>
<script src="/js/plugins/chosen/chosen.jquery.js"></script>
<script src="/js/plugins/jquery-validation/jquery.validate.min.js"></script>
<script src="/js/plugins/dataTables/datatables.min.js"></script>
<script src="/js/plugins/chosen/chosen.ajaxaddition.jquery.js"></script>
<script src="/js/hardware-filter.js"></script>

<link href="/css/plugins/dataTables/fixedHeader.dataTables.min.css" rel="stylesheet">
<link rel="stylesheet" href="/css/plugins/dataTables/responsive.dataTables.min.css">
<script src="/js/plugins/dataTables/dataTables.responsive.min.js"></script>
<script>

    @if ($errors -> count() > 0)
        $("#addAsnMapping").modal({ show: true });
    @endif

    $(document).ready(function () {

        $('.chosen-select').chosen({ width: "100%" });
        $('.make_model').chosen({ width: "100%" });

        $('#shi-hardware-mapping').click(function () {
            $('#shi-hardware-mapping-form').submit();
        });

        $("#technical_spec").on('change', function () {

            $('#asn-filter-form').submit();
        });

        $('#asn-filter-form').submit(function (e) {

            e.preventDefault();
            $('.ajax-loader').show();
            var formData = $(this).serializeArray();

            $('#asset_type').prop("disabled", true).trigger("chosen:updated");
            $('#manufacturer').prop("disabled", true).trigger("chosen:updated");
            $('#make_and_model').prop("disabled", true).trigger("chosen:updated");
            $('#technical_spec').prop("disabled", true).trigger("chosen:updated");

            $.ajax({
                type: "POST",
                url: "/shi-hardware-mapping-search",
                data: formData,
                success: function (value) {

                    $('.ajax-loader').hide();

                    var dataTable = $("#asn-mapping-table").DataTable();

                    // get the html table rows then
                    if ($.fn.DataTable.isDataTable('#asn-mapping-table')) {
                        dataTable.clear();
                        dataTable.destroy();
                    }

                    $("tbody").empty().promise().done(function () {
                        $("tbody").html(value.hardware);
                    });

                    $('#asn-mapping-table').Tabledit({
                        url: '/shi-hardware-mapping-ajax',
                        columns: {
                            identifier: [1, 'asn_mapping_id'],
                            editable: [[2, 'description'], [3, 'AssetType', 'select', JSON.stringify({!!$assettypes!!})], [5, 'make_and_model', 'select', JSON.stringify({!!$hardwareStandardsArray!!})], [6, 'technical_spec', 'select', JSON.stringify({!!$techSpechs!!})]]
    },

        warningClass: 'success',
        mutedClass: 'danger',
        onDraw : function (data) {
            $('#asn-mapping-table tbody').find('tr').each(function (index) {

            });
        },
        onSuccess: function (data) {
            $('.message-div').hide();

            if (data.status == 'success') {
                $('#success').show();
                $('#success p').text(data.message);
            }
            else if (data.status == 'error') {
                $('#error').show();
                $('#error p').text("This mapping cannot be deleted .");
            }
            $('html, body').animate({
                scrollTop: $("#error").offset().top
            }, 1000);

        },
        onFail: function () {
            $('#error').show();
            $('#error p').text("Something went wrong. Please try again.");
            $('html, body').animate({
                scrollTop: $("#error").offset().top
            }, 1000);
        },
        restoreButton : false
                    });
                },
    error: function(value) {

    }
            })
            .done(function () {
        $('#asset_type').prop("disabled", false).trigger("chosen:updated");
        $('#manufacturer').prop("disabled", false).trigger("chosen:updated");
        $('#make_and_model').prop("disabled", false).trigger("chosen:updated");
        $('#technical_spec').prop("disabled", false).trigger("chosen:updated");

        $('#asn-mapping-table').DataTable(
            {
                responsive: true,
                scrollCollapse: false,
                scrollX: false,
                scrollY: false,
                lengthMenu: [
                    [50, 100, 200],
                    ['50', '100', '200']
                ],

                "order": [[2, "asc"]],
                "bFilter": false,
                "bLengthChange": false,
                "bInfo": false,
            }
        );
    });

        });

    

    @can('ASN Hardware Mapping')
    $('#asn-mapping-table').Tabledit({
        url: '/shi-hardware-mapping-ajax',
        columns: {
            identifier: [1, 'asn_mapping_id'],
            editable: [[2, 'description'], [3, 'AssetType', 'select', JSON.stringify({!!$assettypes!!})], [5, 'make_and_model', 'select', JSON.stringify({!!$hardwareStandardsArray!!})], [6, 'technical_spec', 'select', JSON.stringify({!!$techSpechs!!})]]

            },

    warningClass: 'success',
        mutedClass: 'danger',
            onDraw: function(data) {

                $('#asn-mapping-table tbody').find('tr').each(function (index) {

                });
            },
    onSuccess: function (data) {
        $('.message-div').hide();

        if (data.status == 'success') {
            $('#success').show();
            $('#success p').text(data.message);
        }
        else if (data.status == 'error') {
            $('#error').show();
            $('#error p').text("This mapping cannot be deleted .");
        }
        $('html, body').animate({
            scrollTop: $("#error").offset().top
        }, 1000);

    },
    onFail: function () {
        $('#error').show();
        $('#error p').text("Something went wrong. Please try again.");
        $('html, body').animate({
            scrollTop: $("#error").offset().top
        }, 1000);
    },
    restoreButton: false
        });

    @endcan

    $('#asn-mapping-table').DataTable(
        {
            responsive: true,
            scrollCollapse: false,
            scrollX: false,
            scrollY: false,
            lengthMenu: [
                [50, 100, 200],
                ['50', '100', '200']
            ],


            "order": [[2, "asc"]],
            "bFilter": false,
            "bLengthChange": false,
            "bInfo": false,
        }
    );


    $("#make_and_model").change(function () {
        $('#asn-filter-form').submit();
    });

    var delay = (function () {
        var timer = 0;
        return function (callback, ms) {
            clearTimeout(timer);
            timer = setTimeout(callback, ms);
        };
    })();

    $("#searchText").on('keyup change', function () {
        delay(function () {
            $('#asn-filter-form').submit();
        }, 200);
    });

    $(".tabledit-edit-button").click(function () {
        var currentHardware = $(this).closest('tr').children('.shi-asset-details').data("hardware");
        var currentTechSpec = $(this).closest('tr').children('.shi-asset-details').data("tech");
        var assettype = $(this).closest('tr').children('.shi-asset-details').data("asset");
        getHardwareStandards(currentHardware, assettype);
        //getTechSpecs(currentTechSpec,currentHardware);
    });

    $('select[name="AssetType"]').change(function (e) {
        var assettype = this.value;
        getHardwareStandards(0, assettype);
    });

    $('select[name="make_and_model"]').change(function (e) {
        getTechSpecs(0, this.value);
    });
    $(".add_make_and_model").change(function () {
        $.ajax({
            type: "POST",
            data: { id: $(this).val() },
            url: "/assets-filter/listtechnics",
            success: function (data) {
                $('.add_technical_spec').empty().trigger('chosen:updated');

                $.each(data, function (key, value) {
                    $('.add_technical_spec').append($('<option>', {
                        value: value.id,
                        text: value.details
                    })).trigger('chosen:updated');
                })

            }
        });
    });

    });

    function getHardwareStandards(currentHardware, assettype) {
        $.ajax({
            type: "POST",
            url: "/shi-asset-get-hardware",
            dataType: 'json',
            data: { assettype: assettype, "_token": "{{ csrf_token() }}" },
            dataType: 'text',
            success: function (outputfromserver) {
                var data = JSON.parse(outputfromserver);
                $('select[name="make_and_model"]').empty();
                $.each(data, function (key, value) {
                    $('select[name="make_and_model"]')
                        .append($("<option></option>")
                            .attr("value", key)
                            .text(value));
                });
                if (currentHardware != 0) {
                    $('select[name="make_and_model"]').val(currentHardware);
                }
                $('select[name="make_and_model"]').trigger("change");
            }
        });


    }

    function getTechSpecs(currentTechSpec, techSpec) {
        $.ajax({
            type: "POST",
            url: "/shi-asset-get-tech-spec",
            dataType: 'json',
            data: { techSpec: techSpec, "_token": "{{ csrf_token() }}" },
            dataType: 'text',
            success: function (outputfromserver) {
                var data = JSON.parse(outputfromserver);
                $('select[name="technical_spec"]').empty();
                $.each(data, function (key, value) {
                    $('select[name="technical_spec"]')
                        .append($("<option></option>")
                            .attr("value", key)
                            .text(value));
                });
                if (currentTechSpec != 0) {
                    $('select[name="technical_spec"]').val(currentTechSpec);
                }

            }
        });
    }

</script>