//
//   Copyright © 2021,2022 IsardVDI S.L.
//
//   This file is part of DD
//
//   DD is free software: you can redistribute it and/or modify
//   it under the terms of the GNU Affero General Public License as published by
//   the Free Software Foundation, either version 3 of the License, or (at your
//   option) any later version.
//
//   DD is distributed in the hope that it will be useful, but WITHOUT ANY
//   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
//   FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
//   details.
//
//   You should have received a copy of the GNU Affero General Public License
//   along with DD. If not, see <https://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

$(document).on('shown.bs.modal', '#modalAddDesktop', function () {
    modal_add_desktops.columns.adjust().draw();
}); 

$(document).ready(function() {

    update_modal_groups();

    $('.btn-global-resync').on('click', function () {
        $.ajax({
            type: "GET",
            url:"api/resync",
            success: function(data)
            {
                table.ajax.reload();
                // $("#modalImport").modal('hide');
                // users_table.ajax.reload();
                // groups_table.ajax.reload();
            },
            error: function(data)
            {
                alert('Something went wrong on our side...')
            }
        });
    });
    
	// Open new group modal
	$('.btn-new').on('click', function () {
        update_modal_groups()
        $('#modalAddGroup').modal({
            backdrop: 'static',
            keyboard: false
        }).modal('show');
    });

    // Send new group form
    $('#modalAddGroup #send').on('click', function () {
        var form = $('#modalAddGroupForm');
        formdata = form.serializeObject()
        console.log('NEW GROUP')
        console.log(formdata)

        $.ajax({
            type: "POST",
            "url": "/api/group",
            data: JSON.stringify(formdata),
            complete: function(jqXHR, textStatus) {
                switch (jqXHR.status) {
                    case 200:
                        $("#modalAddGroup").modal('hide');
                        table.ajax.reload();
                        break;
                    case 409:
                        new PNotify({
                            title: "Add group error",
                            text: $.parseJSON(jqXHR.responseText)['msg'],
                            hide: true,
                            delay: 3000,
                            icon: 'fa fa-alert-sign',
                            opacity: 1,
                            type: 'error'
                        });
                        break;
                    case 412:
                        new PNotify({
                            title: "Add group error",
                            text: $.parseJSON(jqXHR.responseText)['msg'],
                            hide: true,
                            delay: 3000,
                            icon: 'fa fa-alert-sign',
                            opacity: 1,
                            type: 'error'
                        });
                        break;
                    default:
                        alert("Server error.");
                }
            }
        });

    });

    $('.btn-delete_keycloak').on('click', function () {
        $.ajax({
            type: "DELETE",
            url:"/api/groups/keycloak",
            success: function(data)
            {
                console.log('SUCCESS')
                // $("#modalImport").modal('hide');
                // users_table.ajax.reload();
                // groups_table.ajax.reload();
            },
            error: function(data)
            {
                alert('Something went wrong on our side...')
            }
        });
    });

	//DataTable Main renderer
	var table = $('#groups').DataTable({
        "ajax": {
            "url": "/api/groups",
            "dataSrc": ""
        },
        "language": {
            "loadingRecords": '<i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><span class="sr-only">Loading...</span>',
            "emptyTable": "<h1>You don't have any group created yet.</h1><br><h2>Create one using the +Add new button on top right of this page.</h2>"
        },           
        "rowId": "id",
        "deferRender": true,
        "columns": [
            {
                "className":      'actions-control',
                "orderable":      false,
                "data":           null,
                "width": "80px",
                "defaultContent": '<button id="btn-delete" class="btn btn-xs" type="button"  data-placement="top" ><i class="fa fa-times" style="color:darkred"></i></button>'
                //  \
                //                     <button id="btn-edit" class="btn btn-xs" type="button"  data-placement="top" ><i class="fa fa-pencil" style="color:darkblue"></i></button>'
            },
            { "data": "name", "width": "10px" },
            { "data": "path", "width": "10px" },
            ],
         "order": [[2, 'asc']],
        //  "columnDefs": [ ] 
    } );

    $('#groups').find(' tbody').on( 'click', 'button', function () {
        var data = table.row( $(this).parents('tr') ).data();
        // var closest=$(this).closest("div").parent();
        // var pk=closest.attr("data-pk");
        // console.log(pk)
        switch($(this).attr('id')){
            case 'btn-edit':
                $("#modalEditGroupForm")[0].reset();
                $('#modalEditGroup').modal({
                    backdrop: 'static',
                    keyboard: false
                }).modal('show');
                // $('#modalEditGroup #user-avatar').attr("src","/avatar/"+data.id)
                // setUserDefault('#modalEditGroup', data.id);
                $('#modalEdit').parsley();
            break;
            case 'btn-delete':
                new PNotify({
                    title: 'Confirmation Needed',
                        text: "Are you sure you want to delete group: "+data['name']+"?",
                        hide: false,
                        opacity: 0.9,
                        confirm: {
                            confirm: true
                        },
                        buttons: {
                            closer: false,
                            sticker: false
                        },
                        history: {
                            history: false
                        },
                        addclass: 'pnotify-center'
                    }).get().on('pnotify.confirm', function() {
                        console.log(data)
                        if(data.id == false){
                            $.ajax({
                                type: "DELETE",
                                url:"/api/group",
                                data: JSON.stringify(data),
                                success: function(data)
                                {
                                    table.ajax.reload();
                                },
                                error: function(data)
                                {
                                    alert('Something went wrong on our side...')
                                }
                            });
                        }else{
                            $.ajax({
                                type: "DELETE",
                                url:"/api/group/"+data.id,
                                success: function(data)
                                {
                                    table.ajax.reload();
                                },
                                error: function(data)
                                {
                                    alert('Something went wrong on our side...')
                                }
                            });
                        }
                    }).on('pnotify.cancel', function() {
            });	
            break;
        }
    });
})

function update_modal_groups(){
    $.ajax({
        type: "GET",
        "url": "/api/groups",
        success: function(data)
        {
            $(".groups-select").empty().append(
                '<option value="" default>None</option>'
            )
            data.forEach(element => {
                var groupOrigins = [];
                ['keycloak'].forEach(o => {
                    if (element[o]) {
                        groupOrigins.push(o)
                    }
                })
                $(".groups-select").append(
                    '<option value="' + element.name + '">' + element.name + '</option>'
                )
            });
            $('.groups-select').select2();
        },
        error: function(data)
        {
            alert('Something went wrong on our side...')
        }
    });
}