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

    $('#bulk_actions option[value=""]').prop("selected",true);

    update_groups();

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

    $('#bulk_actions').on('change', function () {
        action=$(this).val();
        names=''
        ids=[]

        if(table.rows('.active').data().length){
            $.each(table.rows('.active').data(),function(key, value){
                names+=value['username']+'\n';
                ids.push({'id':value['id'],'username':value['username']});
            });
            var text = "You are about to "+action+" these users:\n\n "+names
        }else{ 
            $.each(table.rows({filter: 'applied'}).data(),function(key, value){
                ids.push({'id':value['id'],'username':value['username']});
            });
            var text = "You are about to "+action+" "+table.rows({filter: 'applied'}).data().length+" users!\n To all the users in list!"
        }
        console.log(ids)
				new PNotify({
						title: 'Bulk actions on users',
							text: text,
							hide: false,
							opacity: 0.9,
							confirm: {
								confirm: true
							},
							buttons: {
								closer: false,
								sticker: false
							},
							history: {
								history: false
							},
							addclass: 'pnotify-center'
						}).get().on('pnotify.confirm', function() {
                            $.ajax({
                                type: "PUT",
                                url:"/api/users_bulk/"+$('#bulk_actions').val(),
                                data: JSON.stringify(ids),
                                success: function(data)
                                {
                                    console.log('SUCCESS')
                                    $('#bulk_actions option[value=""]').prop("selected",true);
                                    table.ajax.reload();
                                },
                                error: function(data)
                                {
                                    alert('Something went wrong on our side...')
                                    $('#bulk_actions option[value=""]').prop("selected",true);
                                    table.ajax.reload();
                                }
                            });
						}).on('pnotify.cancel', function() {
                            $('#bulk_actions option[value=""]').prop("selected",true);
				});
    } );

    // Open new user modal
	$('.btn-new-user').on('click', function () {
        $("#modalAddUserForm")[0].reset();
        update_groups();
        $.ajax({
            type: "GET",
            "url": "/api/user_password",
            success: function(data)
            {
                $('#modalAddUser #password').val(data)
            },
            error: function(data)
            {
                alert('Something went wrong on our side...')
            }
        });
        $('#modalAddUser #enabled').prop('checked',true).iCheck('update');
        $('#modalAddUser').modal({
            backdrop: 'static',
            keyboard: false
        }).modal('show');
    });

    //has uppercase
    window.Parsley.addValidator('uppercase', {
        requirementType: 'number',
        validateString: function(value, requirement) {
        var uppercases = value.match(/[A-Z]/g) || [];
        return uppercases.length >= requirement;
        },
        messages: {
        en: 'Your password must contain at least (%s) uppercase letter.'
        }
    });

    //has lowercase
    window.Parsley.addValidator('lowercase', {
        requirementType: 'number',
        validateString: function(value, requirement) {
        var lowecases = value.match(/[a-z]/g) || [];
        return lowecases.length >= requirement;
        },
        messages: {
        en: 'Your password must contain at least (%s) lowercase letter.'
        }
    });
    // Send new user form
    $('#modalAddUser #send').on('click', function () {
        var form = $('#modalAddUserForm');
        form.parsley().validate();
        if (form.parsley().isValid()){
            formdata = form.serializeObject()
            // console.log('NEW USER')
            // console.log(formdata)

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

    // $("#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)
    //     }
    // });

    $('#modalEditUser #send').on('click', function () {
        var form = $('#modalEditUserForm');
        form.parsley().validate();
        if (form.parsley().isValid()){
            formdata = form.serializeObject()
            formdata['id']=$('#modalEditUserForm #id').val();
            formdata['username']=$('#modalEditUserForm #username').val();
            console.log('UPDATE USER')
            console.log(formdata)
            $.ajax({
                type: "PUT",
                "url": "/api/user/"+formdata['id'],
                data: JSON.stringify(formdata),
                complete: function(jqXHR, textStatus) {
                    table.ajax.reload();
                    switch (jqXHR.status) {
                        case 200:
                            $("#modalEditUser").modal('hide');
                            break;
                            case 404:
                                new PNotify({
                                    title: "Update user error",
                                    text: $.parseJSON(jqXHR.responseText)['msg'],
                                    hide: true,
                                    delay: 3000,
                                    icon: 'fa fa-alert-sign',
                                    opacity: 1,
                                    type: 'error'
                                });
                                break;
                        case 409:
                            new PNotify({
                                title: "Add user 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 user error",
                                text: $.parseJSON(jqXHR.responseText)['msg'],
                                hide: true,
                                delay: 3000,
                                icon: 'fa fa-alert-sign',
                                opacity: 1,
                                type: 'error'
                            });
                            break;
                        default:
                            alert("Server error.");
                    }
                }
            });
        }
    });
	//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": "enabled", "width": "1px" },
                { "data": "id", "width": "10px" },
                { "data": "roles", "width": "10px" },
                {
                    "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-password" class="btn btn-xs" type="button"  data-placement="top" ><i class="fa fa-lock" style="color:orange"></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>'
                },
                {
                    "className": 'text-center',
                    "data": null,
                    "orderable": false,
                    "defaultContent": '<input type="checkbox" class="form-check-input"></input>',
                    "width": "10px"
                },
                { "data": "username", "width": "10px"},
                { "data": "first", "width": "10px"},
                { "data": "last", "width": "150px"},
                { "data": "email", "width": "10px"},
                { "data": "keycloak_groups", "width": "50px" },
                { "data": "quota", "width": "10px", "default": "-"},
				],
			 "order": [[6, 'asc']],
		"columnDefs": [ {
                            "targets": 1,
                            "render": function ( data, type, full, meta ) {
                                // return '<object data="/static/img/missing.jpg" type="image/jpeg" width="25" height="25"><img src="/avatar/'+full.id+'" title="'+full.id+'" width="25" height="25"></object>'
                                return '<img src="/avatar/'+full.id+'" title="'+full.id+'" width="25" height="25" onerror="if (this.src != \'/static/img/missing.jpg\') this.src = \'/static/img/missing.jpg\';">'
                            }},
                            {
							"targets": 0,
							"render": function ( data, type, full, meta ) {
							  if(full.enabled){
                                    return '<i class="fa fa-check" style="color:lightgreen"></i>'
                                }else{
                                    return '<i class="fa fa-close" style="color:darkred"></i>'
                                };
                            }},
                            {
                                "targets": 2,
                                "render": function ( data, type, full, meta ) {
                                    if(full.roles.length){
                                        return full.roles[0][0].toUpperCase() + full.roles[0].slice(1);
                                    }else{
                                        return '-'
                                    }
                                }},
                            {
                                "targets": 5,
                                "render": function ( data, type, full, meta ) {
                                        return '<b>'+full.username+'</b>'
                                }},
                            {
                            "targets": 9,
                            "render": function ( data, type, full, meta ) {
                                grups = ''
                                full.keycloak_groups.forEach(element => {
                                    grups += '<span class="label label-primary" style="margin: 5px;">' + element + '</span>'
                                })
                                return grups
                            }},
                            {
                                "targets": 10,
                                "render": function ( data, type, full, meta ) {
                                    if(full.quota == false){
                                        return 'Unlimited'
                                    }else{
                                        return full.quota
                                    }
                                }},
							]
	} );

    table.on( 'click', 'tr', function () {
        $(this).toggleClass('active');
        if ($(this).hasClass('active')) {
            $(this).find('input').prop('checked', true);
        } else {
            $(this).find('input').prop('checked', false);
        }
    } );

    // $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()
    //     }
    // } );

    $('#users').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':
                $("#modalEditUserForm")[0].reset();
                $('#modalEditUser').modal({
                    backdrop: 'static',
                    keyboard: false
                }).modal('show');
                $('#modalEditUser #user-avatar').attr("src","/avatar/"+data.id)
                setUserDefault('#modalEditUser', data.id);
                $('#modalEdit').parsley();
            break;
            case 'btn-delete':
                new PNotify({
                    title: 'Confirmation Needed',
                        text: "Are you sure you want to delete user: "+data['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() {
                        $.ajax({
                            type: "DELETE",
                            url:"/api/user/"+data.id,
                            success: function(data)
                            {
                                table.ajax.reload();
                            },
                            error: function(data)
                            {
                                alert('Something went wrong on our side...')
                                table.ajax.reload();
                            }
                        });
                    }).on('pnotify.cancel', function() {
            });	
            break;
            case 'btn-password':
                $("#modalPasswdUserForm")[0].reset();
                $('#modalPasswdUser').modal({
                    backdrop: 'static',
                    keyboard: false
                }).modal('show');
                $('#modalPasswdUserForm #id').val(data.id);
                
                $.ajax({
                    type: "GET",
                    url:"/api/user_password",
                    success: function(data)
                    {
                        $('#modalPasswdUserForm #password').val(data);
                        table.ajax.reload();
                    },
                    error: function(data)
                    {
                        alert('Something went wrong on our side...')
                        table.ajax.reload();
                    }
                });
            break;
        }
    });

    $("#modalPasswdUser #send").on('click', function(e){
        var form = $('#modalPasswdUserForm');
        form.parsley().validate();
        if (form.parsley().isValid()){
            formdata=$('#modalPasswdUserForm').serializeObject();
            
            id=$('#modalPasswdUserForm #id').val();
            $.ajax({
                type: "PUT",
                url:"/api/user_password/" + id,
                data: JSON.stringify(formdata),
                success: function(data)
                {
                    $("#modalPasswdUser").modal('hide');
                    table.ajax.reload();
                    // groups_table.ajax.reload();
                },
                error: function(data)
                {
                    alert('Something went wrong on our side...')
                    table.ajax.reload();
                }
                // statusCode: {
                //     404: function(data) {
                //         // {'error': 'description}. Not able to get responseJSON from received object
                //         alert('User not exists in system!')
                //     },
                //     200: function() {
                //       console.log("Success");
                //     }
                //   },
                // error: function(data)
                // {
                //     alert('Something went wrong on our side...')
                // }
            });
        }
    });

    // 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);
	    // });



        // $('.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();
	    // });

        // $('.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/" + user_id,
            success: function(data)
            {
                console.log(data)
                if (data.enabled) {
                    $(div_id + ' #enabled').iCheck('check')
                }
                $(div_id + ' #id').val(data.id);
                $(div_id + ' #username').val(data.username);
                $(div_id + ' #email').val(data.email);
                $(div_id + ' #firstname').val(data.first);
                $(div_id + ' #lastname').val(data.last);
                if(data.quota == false){
                    $(div_id + ' #quota').val('false')
                }else{
                    $(div_id + ' #quota').val(data.quota);
                }
                $(div_id + ' .groups-select').val(data.keycloak_groups);
                
                // $(div_id + ' .role-moodle-select').val(data.keycloak_roles);
                // $(div_id + ' .role-nextcloud-select').val(data.roles);
                $(div_id + ' .role-keycloak-select').val(data.roles[0]);
                $('.groups-select').trigger('change');

                // $('.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');
    }
});

function update_groups(){
    $(".groups-select").empty()
    $.ajax({
        type: "GET",
        "url": "/api/groups",
        success: function(data)
        {
            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...')
        }
    });
}