(function(){
    var Kycs = function() {

        return {

            init: function() {
                var dt = new Datatable();

                dt.init({
                    src: $("#datatable-kycs"),
                    onSuccess: function (grid) {
                        // execute some code after table records loaded
                    },
                    onError: function (grid) {
                        // execute some code on network or other general error
                    },
                    loadingMessage: 'Loading...',
                    dataTable: {
                        "columns": [
                            {"title": "User", "data": "id", "sortable": false},
                            {"title": "User", "data": "user", "sortable": true},
                            {"title": "Type", "data": "type", "sortable": false},
                            //{"title": "Document", "data": "document_location", "sortable": false},
                            {
                                "title" : "Document",
                                "sortable": false,
                                "data": "document_location",
                                "render": function(data, type, row, meta){
                                    if(type === 'display'){
                                        data = '<a href="' + data + '" target="_blank">' + 'View' + '</a>';
                                    }

                                    return data;
                                }
                            },

                            {"title": "Status", "data": null, "sortable": false},
                            {"title": "Created At", "data": "created_at", "sortable": false},
                            {"title": "Actions", "data": null, "sortable": false}
                        ],
                        "columnDefs": [
                            {
                                "targets": [0],
                                "render": function (data, type, full, meta) {
                                   return ' <button class="btn yellow viewUser" data-id="' + full.userid + '"><i class="fa fa-eye"></i>Details</button>';
                                }
                            },
                            {
                                "visible": false,
                                "targets": [1]
                            },
                            {
                                "targets": [4],
                                "render": function (data, type, full, meta) {
                                    var label_style = 'default';
                                    var label_content = 'Pending';
                                    if (full.status === 1) {
                                        label_style = 'success';
                                        label_content = 'Approved';
                                    }
                                    else if (full.status === 2) {
                                        label_style = 'danger';
                                        label_content = 'Rejected';
                                    }

                                    return '<span class="label label-' + label_style + '"> ' + label_content + ' </span>';
                                }
                            },
                            {
                                "targets": [6],
                                "render": function (data, type, full, meta) {
                                    var btn = '<a href="' + admin_kycs_edit + '/' + full.id + '" class="btn btn-sm yellow" id="edit"><i class="fa fa-pencil"></i> Edit</a>';

                                    if( full.status === 0 ||  full.status === null) {
                                        btn += '<button class="btn btn-danger changeStatusBtn btn-sm" style="margin-right:10px" data-action="2" data-id="' + full.id + '"><i class="fa fa-close"></i> Reject </button>';
                                        //} else {
                                        btn += '<button class="btn btn-success changeStatusBtn btn-sm" style="margin-right:10px" data-action="1" data-id="' + full.id + '"><i class="fa fa-check"></i> Approve </button>';
                                        //}
                                    }

                                    btn += '<button class="btn btn-sm red" id="remove" data-id="' + full.id + '"><i class="fa fa-close"></i> Delete</button>';

                                    return btn;
                                }

                            }
                        ],
                        "pageLength": 25, // default record count per page
                        "ajax": {
                            "url": ajax_kycs_dt // ajax source,
                        },
                        "order": [
                            [1, "asc"]
                        ], // set first column as a default sort by asc

                        "drawCallback": function (settings) {
                            var api = this.api();
                            var rows = api.rows({
                                page: 'current'
                            }).nodes();

                            //console.log( api.rows( {page:'current'} ).data() );

                            //debugger;

                            /*      rows.forEach(function(node) {
                             console.log("rows =" + node);
                             }); */


                            var last = null;

                            api.column(1, {
                                page: 'current'
                            }).data().each(function (group, i) {


                            for(var i = 0; i < api.rows( {page:'current'} ).data().length; i++) {

                                if (api.rows({page: 'current'}).data()[i]['user'] === group) {

                                    if (last !== group) {
                                        $(rows).eq(i).before(
                                            '<tr class="group"><td colspan="6">' + group + ' <button class="btn btn-success btn-sm verifyBtn" style="margin-right:10px; float: right;" data-action="2" data-id="' + api.rows({page: 'current'}).data()[i]['userid'] + '"><i class="fa fa-check"></i> Open detailed view </button></td></tr>'
                                        );

                                        last = group;

                                        break;
                                    }
                                }
                            }

                            });

                            $('tbody [role=row]').each(function(){
                                //console.log($(this));
                                $(this).css("display", "none");
                            });

                            //$('.label-default').parents('tr').css('background-color', '#f0ece2');
                            $('.label-success').parents('tr').css('background-color', '#defcfc');
                            $('.label-danger').parents('tr').css('background-color', '#f7ddde');

                            if(window.active_group){
                                $('tbody .group').each(function(){
                                    //console.log($(this));
                                    if($(this).children().text() === window.active_group){
                                        $(this).nextUntil(':not([role=row])').show();
                                    }
                                });
                            }
                        }
                    }
                });

                $('#datatable-kycs').on('click', 'tbody td:last-child button#remove', function(e){
                    window.active_group = $(this).parent().parent().prevAll('.group:first').children().text();

                    e.preventDefault();

                    var self = $(this);

                    App.ajax({
                        url: ajax_kycs_delete,
                        type: 'POST',
                        data: {
                            id: self.data('id')
                        }
                    }, function( data ){

                        //console.log(window.active_group);
                        dt.getDataTable().ajax.reload();
                    });

                });

                $('#datatable-kycs').on('click', 'tbody tr td:last-child .changeStatusBtn', function() {
                        var id = $(this).data('id');
                        var code = $(this).data('action');
                        window.active_group = $(this).parent().parent().prevAll('.group:first').children().text();

                        App.ajax({
                            url: ajax_kycs_status,
                            type: 'POST',
                            data: {
                                id: id,
                                code: code
                            }
                        }, function(data){
                            if( data ) {
                                dt.getDataTable().ajax.reload();
                            }
                        });

                    });
      
                $('#datatable-kycs').on('click', 'tbody tr td:last-child .verifyBtn', function() {
                    var id = $(this).data('id');


                        window.location.href= user_kycs+'/'+id;


                });
                $('#datatable-kycs').on('click', ' tbody tr td .viewUser', function(e) {

                    e.preventDefault();
                    var id = $(this).data('id');
                    App.userInfo( id, userInfoUrl );
                 });
            }
        }

    }();

    $(document).ready(function() {
        Kycs.init();


        // Order by the grouping
        $('#datatable-kycs tbody').on('click', function({target}) {
            if (target.parentNode.className !== 'group') return;
            //console.log($(this).find('[role=row]'))
            $(target.parentNode).nextUntil(':not([role=row])').slideToggle();

        });


    });

})();