
function initFileUploader(){
    $('#fileupload').fileupload({
        url: '{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/upload-key-file',
        type: 'POST',
        autoUpload: true,
        multipart: true,
        acceptFileTypes: /(\.|\/)(csv)$/i,
        maxFileSize: 1000000,
        maxNumberOfFiles: 1
    }).bind('fileuploaddone', function (e, data) {
        var response;
        if (data && data.jqXHR && data.jqXHR.status && data.jqXHR.status == 200 && data.jqXHR.responseJSON) {
            response = data.jqXHR.responseJSON;
        } else {
            JSErrorModalBox();
            return false;
        }
        if (response.success) {
            ajaxSuccess(response, false);
        }
        return false;
    }).bind('fileuploadfail', function (e, data) {
        if (data && data.jqXHR && data.jqXHR.status && data.jqXHR.responseJSON) {
            JSErrorModalBox(data.jqXHR.responseJSON);
        } else {
            JSErrorModalBox();
        }
    });
    return true;
}

function TestTable1() {
    $('#datatable-1').on('xhr.dt', function (e, settings, json) {
        if (typeof (json.data) == 'object') {
            for (var i in json.data) {
                json.data[i] = rowDataPrepare(json.data[i]);
            }
        }
    }).dataTable({
        "processing": true,
        "serverSide": true,
        "ajax" : {
            "url" : "{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/license-keys-list-json"
        },
        "language": {
            "url": "{{ app.datatable_lang_file }}"
        },

        "bFilter": true,
        "lengthChange": true,
        "bPaginate": true,
        "bInfo": true,

        "fixedHeader": {
            header: true,
            headerOffset: $('header.navbar').height()
        },
        
        select: {
            style:    'multi',
            selector: 'td.select-checkbox'
        },
        rowId: "RowOrder", // required to restore selected rows on reload
        "sDom": "<'clearfix'<'pull-right'fA><'button-place'B>>rt<'row-fluid'<'col-md-4 no-padding'i><'col-md-8 no-padding'pl>>",

        "order": [[ 1, "desc" ]],
        "columns": [
            { "data": null, defaultContent: "", orderable: false, /*visible: true,*/ className: 'w-1p select-checkbox'},
        {% for key, item in app['dropdownAttribute'] %}
            {% if 'all' != item.name %}
            {"data": "{{ item.name }}", /**/ "name": "{{ item.name }}" {% if not(item.checked) %}, visible: false, className: 'none'{% endif %}}{% if not loop.last %},{% endif %}
            {% endif %}
        {% endfor %}
        ],

        "aoColumnDefs": [
            {"searchable": false, "targets": [ 0, -1, -5 ]},
            {"sortable": false, "targets": [ 0, -1 ]},
            {"className": "dt-status", "targets": 5 }
        ],


        // remove column.visible from stateSave 
        // the DT was applying the column visibility setting from stateSave after dropdown filter
        "stateSaveParams": function (settings, data) {
                                data.columns.forEach(
                                    function(item) {
                                        item.visible = null;
                                        delete item.visible;
                                });
                            },


        "buttons": [
            
            // Switch on/off
            {   
                extend: 'collection',
                // params are described here:
                // https://datatables.net/reference/button/collection
                text: '<i class="fa fa-toggle-on"></i> {{ 'Switch on/off'|trans }} <i class="fa fa-caret-down"></i>',
                autoClose: true,
                background: true,
                //backgroundClassName: "dt-button-background",
                fade: 0, // speed 
                buttons: [
                    {
                        text: '{{ 'Switch on'|trans }}',
                        action: function ( e, dt, node, config ) {
                            e.stopPropagation();
                            e.preventDefault();
                            JScloseModalBox();
                            
                            var sendData = {};
                            var ids = dt.rows( { selected: true } ).ids().toArray().toString().replace(/dTRow_/g, "" );
                            sendData.group_key = "id";
                            sendData.id = ids;
                            sendData.action = "active";

                            if ((sendData.id).search(',') != -1){
                                sendData.id = JSON.stringify(sendData.id.split(','));
                            }

                            ajaxPostSend( "{{app.request_context.baseUrl}}/{{ app.controller_alias }}/toggle-key-status", sendData, false, false, true);
                            
                        }
                    },
                    {
                        text: '{{ 'Switch off'|trans }}',
                        action: function ( e, dt, node, config ) {
                            e.stopPropagation();
                            e.preventDefault();
                            JScloseModalBox();

                            var sendData = {};
                            var ids = dt.rows( { selected: true } ).ids().toArray().toString().replace( /dTRow_/g, "" );
                            sendData.group_key = "id";
                            sendData.id = ids;
                            sendData.action = "block";

                            if ((sendData.id).search(',') != -1){
                                sendData.id = JSON.stringify(sendData.id.split(','));
                            }

                            ajaxPostSend( "{{app.request_context.baseUrl}}/{{ app.controller_alias }}/toggle-key-status", sendData, false, false, true);

                        }
                    }
                ]
            }
        ]
    }).prev('.dataTables_processing').hide(50);
}

function yelp() {
    $(document).ready(function () {

        LoadDataTablesScripts(TestTable1);

        if (typeof (loadFileUploadScripts) != 'function' || !loadFileUploadScripts(initFileUploader)){
            JSErrorModalBox({msg: "{{ 'Cannot load File Upload plugin'|trans }}"})
        }

        var table = $('#datatable-1').DataTable();

        table
            .on( 'select', function ( e, dt, type, indexes ) {

                var rows = dt.rows( { selected: true } ).count();
                
                $(".dt-buttons .dt-button").show().removeClass( "disabled" );

                if ( rows == dt.rows().count() ){
                    setGroupSelectState( "all" );
                } else {
                    setGroupSelectState( "some" );
                }

            } )
            .on( 'deselect', function ( e, dt, type, indexes ) {

                var rows = dt.rows( { selected: true } ).count();
                
                if ( rows >= 1 ) {
                    $(".dt-buttons .dt-button").show().removeClass( "disabled" );
                    setGroupSelectState( "some" );
                } else if ( rows == 0 ) {
                    setGroupSelectState( "none" );
                    resetTableButtons();
                }

            } )

            // expand Processing width for overflow table
            .on( 'processing.dt', function ( e, settings, processing ) {
                $(settings.aanFeatures.r).css( 'width', $(settings.aanFeatures.t).width() );
            } )

            // refresh filter(search) results when col-vis is changed:
            .on( 'column-visibility.dt', function ( e, settings, column, state ) {
                
                if ( table.search() ) {
                    table.draw("page");
                }

            } );

            // reset Buttons on Paging reload 
            $('#datatable-1').on( 'page.dt', function () {
                resetTableButtons( );
                setGroupSelectState( "none" );
            } );

            // Reinit group actions Table Buttons
            $('#datatable-1').on( 'draw.dt', function ( e, settings ) {
                if( table.rows( { selected: true } ).ids().length == 0 ) {
                    resetTableButtons(); 
                    setGroupSelectState('none');
                }
            } );


            // Select dropdowns 
            $( "#select_all" ).click( function(e){
                if( !$(this).hasClass("disabled") ) {
                    table.rows().select();
                }
            });

            $( "#select_none" ).click( function(e){
                if( !$(this).hasClass("disabled") ) {
                    table.rows().deselect();
                }
            });

            $( "#select_inverse" ).click( function(e){
                if( !$(this).hasClass("disabled") ) {
                    var rowsSelected = table.rows( { selected: true } );
                    table.rows().select();
                    rowsSelected.deselect();
                }
            });

            // Disable annoying message on disabled buttons
            $(document).off('click', "a[disabled], a.disabled");

            setTimeout( initTableButtons, 200 );



        $(document).on('click', "a.main_ajax:not([disabled])", function (e) {
            e.stopPropagation();
            e.preventDefault();
            var _this = this;
            $("#modalbox").data('complete', 0);
            var sendData = $(_this).data();
            ajaxPostSend($(_this).attr('href'), sendData, false );
            $(this).closest('div.open').removeClass('open');
            return false;
        });

        $(document).on('change', ".mswitch input", function(e){
            ajaxPostSend('{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/toggle-key-status', $(this).data() );
        });

    });
}

document.addEventListener("DOMContentLoaded", yelp, false);

function rowDataPrepare(item){

    if (item['added'] != 0) {
        var dateOn = new Date(item['added']);
        item['added'] = dateOn.toLocaleFormat("%b %d, %Y").replace(" ", "&nbsp;");
    }
    item.user_id = item.user_id.toString() !== '0' ? "<a href='{{ app.request_context.baseUrl }}/users/edit-users?id=" + item.user_id + "'>" + item.user_id + "</a>": '-';
    item.action = '<div class="mswitch">\n\
                      <input type="checkbox" id="key_'+ item.id +'" name="status" readonly="readonly" class="form-control" ' + ( item.action !== 'active' ? 'checked="checked"' : '' ) + ' data-id="' + item.id + '" data-action="'+ item.action +'" ' + ( item.action == 'ignore' ? 'disabled="disabled"': '') + '>\n\
                      <label class="label-success" title="' + ( item.action !== 'active' ? "{{ 'Active'|trans }}" : "{{ 'Blocked'|trans }}" ) + '" for="key_'+ item.id +'"></label>\n\
                   </div>';
    var status_classes = {
        'activated' : 'skyblue',
        'manually_entered': 'green',
        'not_activated': 'no-monitoring',
        'blocked': 'red'
    }
    item.status = '<span class="monitoring-status ' + (status_classes[item.status_flag] ? status_classes[item.status_flag]: '') + ' nowrap">' +item.status +'</span>';
    {% autoescape false %}
    var key_types = {
        {% for row in app.allKeyTypes %}
            {{ row.id }}: '{{ row.title }}'{% if not(loop.last) %}{{ ',' }}{% endif %}
        {% endfor %}
    }
    {% endautoescape %}
    item.key_type = key_types[item.key_type] || item.key_type;
    return item;
}


function initTableButtons() { 
    $(".dt-group-select-dropdown").prependTo( $(".dataTables_wrapper .dt-buttons").first() );
    resetTableButtons();
}

function resetTableButtons() { 
    $(".dt-buttons .dt-button").not(".dt-group-select-dropdown .dt-button").addClass( "disabled" ).hide();
}

function setGroupSelectState(state) {
    if ( typeof state != "string" ){
        return;
    }

    $(".dt-group-select-dropdown").removeClass( "all none some" ).addClass( state );
    
    $("#select_all, #select_none, #select_inverse").removeClass( "disabled" );
        
        switch( state ) {
    
    case "none": $("#select_none, #select_inverse").addClass( "disabled" );
                 break;

    case "all":  $("#select_all").addClass( "disabled" );
                 break;
    }
}