//
//   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() {

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

    $.ajax({
        type: "GET",
        "url": "/api/roles",
        success: function(data)
        {
            console.log('ROLES')
            console.log(data)
            data.forEach(element => {
                $(".role-moodle-select, .role-nextcloud-select, .role-keycloak-select").append(
                '<option value=' + element.id + '>' + element.name + '</option>'
                )
            })
        },
        error: function(data)
        {
            alert('Something went wrong on our side...')
        }
    });

    $('.btn-global-resync').on('click', function () {
        $.ajax({
            type: "GET",
            url:"/api/resync",
            success: function(data)
            {
                console.log('Reloaded')
                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 user modal
	$('.btn-new-user').on('click', function () {
        $('#modalAddUser').modal({
            backdrop: 'static',
            keyboard: false
        }).modal('show');
    });

    // Send new user form
    $('#modalAddUser #send').on('click', function () {
        var form = $('#modalAddUserForm');
        formdata = form.serializeObject()
        console.log('NEW USER')
        console.log(formdata)
        // $.ajax({
        //     type: "POST",
        //     "url": "/groups_list",
        //     success: function(data)
        //     {
        //         console.log('SUCCESS')
        //         // $("#modalAddUser").modal('hide');
        //     },
        //     error: function(data)
        //     {
        //         alert('Something went wrong on our side...')
        //     }
        // });
    });

    $('.btn-delete_keycloak').on('click', function () {
        new PNotify({
            title: 'Confirmation Needed',
            text: "Are you sure you want to DELETE ALL USERS IN KEYCLOAK???",
            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('Updating user password...')
            $.ajax({
                type: "DELETE",
                url:"/api/users/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...')
                }
            });
        }).on('pnotify.cancel', function() {
        });


    });

    $('.btn-delete_nextcloud').on('click', function () {
        new PNotify({
            title: 'Confirmation Needed',
            text: "Are you sure you want to DELETE ALL USERS IN NEXTCLOUD?",
            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('Updating user password...')
            $.ajax({
                type: "DELETE",
                url:"/api/users/nextcloud",
                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...')
                }
            });
        }).on('pnotify.cancel', function() {
        });
    });

    $('.btn-delete_moodle').on('click', function () {
        new PNotify({
            title: 'Confirmation Needed',
            text: "Are you sure you want to DELETE ALL USERS IN MOODLE?",
            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('Updating user password...')
            $.ajax({
                type: "DELETE",
                url:"/api/users/moodle",
                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...')
                }
            });
        }).on('pnotify.cancel', function() {
        });
    });

    $('.btn-sync_to_moodle').on('click', function () {
        $.ajax({
            type: "POST",
            url:"/api/users/moodle",
            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...')
            }
        });
    });


    $('.btn-sync_from_keycloak').on('click', function () {
        $.ajax({
            type: "PUT",
            url:"/api/users",
            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...')
            }
        });
    });

    $('.btn-sync_to_nextcloud').on('click', function () {
        $.ajax({
            type: "POST",
            url:"/api/users/nextcloud",
            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 = $('#users').DataTable({
			"ajax": {
				"url": "/api/users",
				"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 user 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":      'details-control',
                "orderable":      false,
                "data":           null,
                "width": "10px",
                "defaultContent": '<button class="btn btn-xs btn-info" type="button"  data-placement="top" ><i class="fa fa-plus"></i></button>'
				},
                { "data": "id", "width": "10px" },
				{ "data": "username", "width": "10px"},
				{ "data": "first", "width": "10px"},
				{ "data": "last", "width": "10px"},
                { "data": "email", "width": "10px"},
                { "data": "keycloak", "width": "10px" },
                { "data": "keycloak_groups", "width": "10px" },
                { "data": "roles", "width": "10px" },
                { "data": "moodle", "width": "10px" },
                { "data": "moodle_groups", "width": "10px" },
                { "data": "nextcloud", "width": "10px" },
                { "data": "nextcloud_groups", "width": "10px" },
				],
			 "order": [[4, 'asc']],		 
		"columnDefs": [ {
                            "targets": 1,
                            "render": function ( data, type, full, meta ) {
                                    return '<img src="/avatar/'+full.id+'" title="'+full.id+'" width="25" height="25">'
                            }},
                            {
							"targets": 6,
							"render": function ( data, type, full, meta ) {
							  if(full.keycloak){
                                    return '<i class="fa fa-check" style="color:lightgreen"></i>'
                                }else{
                                    return '<i class="fa fa-close" style="color:darkred"></i>'
                                };
                            }},
                            {
                            "targets": 7,
                            "render": function ( data, type, full, meta ) {
                                return "<li>" + full.keycloak_groups.join("</li><li>") + "</li>"
                            }},
                            {
                            "targets": 9,
                            "render": function ( data, type, full, meta ) {
                                if(full.moodle){
                                    return '<i class="fa fa-check" style="color:lightgreen"></i>'
                                }else{
                                    return '<i class="fa fa-close" style="color:darkred"></i>'
                                };
                            }},
                            {
                                "targets": 10,
                                "render": function ( data, type, full, meta ) {
                                    return "<li>" + full.moodle_groups.join("</li><li>") + "</li>"
                                }},
                            {
                            "targets": 11,
                            "render": function ( data, type, full, meta ) {
                                if(full.nextcloud){
                                    return '<i class="fa fa-check" style="color:lightgreen"></i>'
                                }else{
                                    return '<i class="fa fa-close" style="color:darkred"></i>'
                                };
                            }},
                            {
                                "targets": 12,
                                "render": function ( data, type, full, meta ) {
                                    return "<li>" + full.nextcloud_groups.join("</li><li>") + "</li>"
                                }},
							]
	} );

    $template = $(".template-detail-users");

    $('#users').find('tbody').on('click', 'td.details-control', function () {
        var tr = $(this).closest('tr');
        var row = table.row( tr );
 
        if ( row.child.isShown() ) {
            // This row is already open - close it
            row.child.hide();
            tr.removeClass('shown');
        }
        else {
            // Close other rows
            if ( table.row( '.shown' ).length ) {
                $('.details-control', table.row( '.shown' ).node()).click();
            }
            // Open this row
            row.child( addUserDetailPannel(row.data()) ).show();
            tr.addClass('shown');
            actionsUserDetail()
        }
    } );

    function addUserDetailPannel ( d ) {
		$newPanel = $template.clone();
		$newPanel.html(function(i, oldHtml){
			return oldHtml.replace(/d.id/g, d.id).replace(/d.username/g, d.username);
		});
		return $newPanel
    }

    function actionsUserDetail(){

        $('.btn-passwd').on('click', function () {
            var closest=$(this).closest("div").parent();
            var pk=closest.attr("data-pk");
            $("#modalPasswdUserForm")[0].reset();
			$('#modalPasswdUser').modal({
				backdrop: 'static',
				keyboard: false
			}).modal('show');
            $('#modalPasswdUserForm #id').val(pk);
	    });

        $("#modalPasswdUser #send").on('click', function(e){
            var form = $('#modalPasswdUserForm');
            form.parsley().validate();
            if (form.parsley().isValid()){
                data=$('#modalPasswdUserForm').serializeObject();
                data['id']=$('#modalPasswdUserForm #id').val();
                new PNotify({
                    title: 'Confirmation Needed',
                    text: "Are you sure you want to update password for the user "+ username+"?",
                    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('Updating user password...')
                    $.ajax({
                        type: "PUT",
                        url:"/api/user" + id,
                        success: function(data)
                        {
                            $(div_id + ' #id').val(data.id);
                            $(div_id + ' #username').val(data.username);
                            $(div_id + ' #email').val(data.email);
                            $(div_id + ' #firstname').val(data.firstname);
                            $(div_id + ' #lastname').val(data.lastname);
                            $(div_id + ' .groups-select').val(data.groups);
                            $(div_id + ' .role-moodle-select').val(data.roles);
                            $(div_id + ' .role-nextcloud-select').val(data.roles);
                            $(div_id + ' .role-keycloak-select').val(data.roles);
                            $('.groups-select, .role-moodle-select, .role-nextcloud-select, .role-keycloak-select').trigger('change'); 
                        }
                    });
                }).on('pnotify.cancel', function() {
                });
            }
        });

        $('.btn-edit').on('click', function () {
            var closest=$(this).closest("div").parent();
            var pk=closest.attr("data-pk");
            $("#modalEditUserForm")[0].reset();
			$('#modalEditUser').modal({
                backdrop: 'static',
				keyboard: false
			}).modal('show');
            setUserDefault('#modalEditUser', pk);
            $('#modalEdit').parsley();
	    });

        $("#modalEditUser #send").on('click', function(e){
            var form = $('#modalEditUserForm');
            form.parsley().validate();
            if (form.parsley().isValid()){
                data=$('#modalEditUserForm').serializeObject();
                data['id']=$('#modalEditUserForm #id').val();
                console.log('Editing user...')
                console.log(data)
            }
        });

        $('.btn-delete').on('click', function () {
            var closest=$(this).closest("div").parent();
            var pk=closest.attr("data-pk");
            var username=closest.attr("data-username");
            console.log(username)
            new PNotify({
                title: 'Confirmation Needed',
                text: "Are you sure you want to delete the user: "+ username+"?",
                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('Deleting user...')
            }).on('pnotify.cancel', function() {
            });
        });
    }
    function setUserDefault(div_id, user_id) {
        // $.ajax({
        //     type: "GET",
        //     url:"/api/user/" + id,
        //     success: function(data)
        //     {
        //         $(div_id + ' #id').val(data.id);
        //         $(div_id + ' #username').val(data.username);
        //         $(div_id + ' #email').val(data.email);
        //         $(div_id + ' #firstname').val(data.firstname);
        //         $(div_id + ' #lastname').val(data.lastname);
        //         $(div_id + ' .groups-select').val(data.groups);
        //         $(div_id + ' .role-moodle-select').val(data.roles);
        //         $(div_id + ' .role-nextcloud-select').val(data.roles);
        //         $(div_id + ' .role-keycloak-select').val(data.roles);
        //         $('.groups-select, .role-moodle-select, .role-nextcloud-select, .role-keycloak-select').trigger('change'); 
        //     }
        // });
        // MOCK
        $(div_id + ' #id').val('b57c8d3f-ee08-4a1d-9873-f40c082b9c69');
        $(div_id + ' #user-avatar').attr('src', '/static/img/usera.jpg');
        $(div_id + ' #username').val('yedcaqwvt');
        $(div_id + ' #email').val('yedcaqwvt@institutmariaespinalt.cat');
        $(div_id + ' #firstname').val('Ymisno');
        $(div_id + ' #lastname').val('Edcaqwvt tavnuoes');
        $(div_id + ' .groups-select').val(['student', 'manager']);
        $(div_id + ' .role-moodle-select').val('51cc1a95-94b7-48eb-aebb-1eba6745e09f');
        $(div_id + ' .role-nextcloud-select').val('1e21ec95-b8c7-43b8-baad-1a31ad33f388');
        $(div_id + ' .role-keycloak-select').val('13da53d5-c50b-42d9-8fbf-84f2ed7cbf9e');
        $('.groups-select, .role-moodle-select, .role-nextcloud-select, .role-keycloak-select').trigger('change');
    }
});