//
//   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() {
    $('#action_role option[value=""]').prop("selected",true);
    var path = "";
    items = [];
    document.getElementById('file-upload').addEventListener('change', readFile, false);
	$('.btn-upload').on('click', function () {
        $('#modalImport').modal({backdrop: 'static', keyboard: false}).modal('show');
        $('#modalImportForm')[0].reset();
	});

    $('.btn-sync').on('click', function () {
        ids={}
        $.each(users_table.rows().data(),function(key, value){
            ids[value['id']]=value['roles']
        });
        // console.log(ids)
        $.ajax({
            type: "PUT",
            url:"/api/external",
            data: JSON.stringify(ids),
            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-clear-upload').on('click', function () {
        new PNotify({
            title: 'Cleaning imported data',
                text: 'Are you sure you want to clean imported data?',
                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/external",
                    success: function(data)
                    {
                        console.log('SUCCESS')
                        users_table.ajax.reload();
                        groups_table.ajax.reload();
                    },
                    error: function(data)
                    {
                        alert('Something went wrong on our side...')
                    }
                });
            }).on('pnotify.cancel', function() {
                $('#action_role option[value=""]').prop("selected",true);
            });

    });

	$('.btn-sample').on('click', function () {
        var viewerFile = new Blob(["groups;firstname;lastname;email;username;password;password_temporal;role;quota\n/alumnes/6è;John;Doe;jdoe@digitaldemocratic.net;jdoe;SuperSecret;no;student;1GB\n/alumnes/6è;Magdalena;Martí;mm_profe@email.cat;mm_profe;SuperSecret;no;teacher;3GB\n/managers;Pere;Isard;pisardmgr@email.cat;pisardmgr;SuperSecret;no;manager;Unlimited\n/alumnes/4t,/alumnes/5è;Marc;Gómez;marcgt@email.cat;marcgt;SuperSecret;no;student;1GB"], {type: "text/csv"});
        var a = document.createElement('a');
            a.download = 'dd_sample_upload.csv';
            a.href = window.URL.createObjectURL(viewerFile);
        var ev = document.createEvent("MouseEvents");
            ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            a.dispatchEvent(ev);  
	});

    $('.btn-download').on('click', function () {

        data=users_table.rows().data()
        csv_data='TYPE,EXT_ID,EMAIL,FIRST,LAST,USERNAME,PATHS,GROUPS,QUOTA,ROLE,PASS_TEMP,PASSWORD'+ '\r\n'
        csv_data=csv_data+convertToCSV(data)
        console.log(csv_data)
        exportCSVFile(csv_data, 'users_data')
    })

    $("#modalImport #send").on('click', function(e){
        // console.log(users_table.rows().data())
        var form = $('#modalImportForm');
        form.parsley().validate();
        if (form.parsley().isValid()){
            formdata = form.serializeObject()
            if($('#format').val() == 'csv-ug'){
                formdata['data']=parseCSV(filecontents)
            }else{
                formdata['data']=JSON.parse(filecontents)
            }
            $.ajax({
                type: "POST",
                url:"/api/external",
                data: JSON.stringify(formdata),
                success: function(data)
                {
                    console.log('SUCCESS')
                    $("#modalImport").modal('hide');
                    users_table.ajax.reload();
                    groups_table.ajax.reload();
                },
                error: function(xhr, status, error) {
                    var err = eval("(" + xhr.responseText + ")");
                    alert(JSON.parse(xhr.responseText).msg)
                    users_table.ajax.reload();
                    groups_table.ajax.reload();
                  }
            });
        }
    });

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

        if(users_table.rows('.active').data().length){
            $.each(users_table.rows('.active').data(),function(key, value){
                names+=value['name']+'\n';
                ids.push(value['id']);
            });
            var text = "You are about to assign role "+action+" these users:\n\n "+names
        }else{ 
            $.each(users_table.rows({filter: 'applied'}).data(),function(key, value){
                ids.push(value['id']);
            });
            var text = "You are about to assign role "+action+" "+users_table.rows({filter: 'applied'}).data().length+" users!\n All the users in list!"
        }
				new PNotify({
						title: 'Role assignment!',
							text: 'You will asign the role '+action,
							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/external/roles",
                                data: JSON.stringify({'ids':ids,'action':action}),
                                success: function(data)
                                {
                                    console.log('SUCCESS')
                                    users_table.ajax.reload();
                                    groups_table.ajax.reload();
                                },
                                error: function(data)
                                {
                                    alert('Something went wrong on our side...')
                                }
                            });
						}).on('pnotify.cancel', function() {
                            
                });
                $('#action_role option[value=""]').prop("selected",true);
    } );

	//DataTable Main renderer
	var users_table = $('#users').DataTable({
			"ajax": {
				"url": "/api/external/users",
				"dataSrc": ""
			},
			"language": {
				"loadingRecords": '<i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><span class="sr-only">Loading...</span>',
                "emptyTable": "<h2>No users imported yet.</h2><br><h2>Import with the Upload 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": "provider", "width": "10px" },
                { "data": "id", "width": "10px" },
				{ "data": "username", "width": "10px"},
				{ "data": "first", "width": "10px"},
				{ "data": "last", "width": "10px"},
                { "data": "email", "width": "10px"},
                { "data": "gids", "width": "10px"},
                { "data": "groups", "width": "10px"},
                { "data": "roles", "width": "10px"},
                { "data": "quota", "width": "10px"},
                { "data": "password", "width": "10px"},
				],
			 "order": [[3, 'asc']],		 
             "columnDefs": [ {
                "targets": 1,
                "render": function ( data, type, full, meta ) {
                    return '<img src="/custom/avatars/'+full.roles+'.jpg" title="'+full.id+'" width="25" height="25" onerror="if (this.src != \'/static/img/missing.jpg\') this.src = \'/static/img/missing.jpg\';">'
                    return '<img src="/avatar/'+full.id+'" title="'+full.id+'" width="25" height="25">'
                }},
                {
                "targets": 6,
                "render": function ( data, type, full, meta ) {
                    return "<li>" + full.gids.join("</li><li>") + "</li>"
                }},
                {
                    "targets": 7,
                    "render": function ( data, type, full, meta ) {
                    return "<li>" + full.groups.join("</li><li>") + "</li>"
                }}
             ]
    } );


	var groups_table = $('#groups').DataTable({
        "ajax": {
            "url": "/api/external/groups",
            "dataSrc": ""
        },
        "language": {
            "loadingRecords": '<i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><span class="sr-only">Loading...</span>',
            "emptyTable": "<h2>No groups imported yet.</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": "provider", "width": "10px" },
            { "data": "name", "width": "10px" },
            { "data": "description", "width": "10px"},
            ],
         "order": [[2, 'asc']],		 
    "columnDefs": [ ]
} );
});

function readFile (evt) {
    if($('#format').val() == 'json-ga'){
        path = "";
        items = [];
        var files = evt.target.files;
        var file = files[0];
        var reader = new FileReader();
        reader.onload = function(event) {
            filecontents=event.target.result;
            $.each(JSON.parse(filecontents), walker);
            populate_path(items)
        }
        reader.readAsText(file, 'UTF-8')
    }
    if($('#format').val() == 'csv-ug'){
        var files = evt.target.files;
        var file = files[0];
        var reader = new FileReader();
        reader.onload = function(event) {
            filecontents=event.target.result;
            // $.each(JSON.parse(filecontents), walker);
            // populate_path(items)
        }
        reader.readAsText(file, 'UTF-8')
    }
    
 }

function parseCSV(){
    lines=filecontents.split('\n')
    header=lines[0].split(';')
    users=[]
    $.each(lines, function(n, l){
        if(n!=0 && l.length > 10){
            usr=toObject(header,l.split(';'))
            usr['id']=usr['username']
            users.push(usr)
        }
    })
    return users;
}
 function toObject(names, values) {
     var result = {};
     for (var i = 0; i < names.length; i++)
          result[names[i]] = values[i];
     return result;
 }

function walker(key, value) {
    var savepath = path;
    path = path ? (path + "/" + key) : key;
    items.push({path:path})

    if (typeof value === "object") {
        // Recurse into children
        if(value.constructor === Array){
            value=value[0]
        }
        if(typeof value == "object"){
            $.each(value, walker);
        }
    }

    path = savepath;
}

function populate_path(){
    $.each(items, function(key, value) {
        $(".populate").append('<option value=' + value['path']+ '>' + value['path'] + '</option>');
    })
}

function convertToCSV(objArray) {
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '';

    for (var i = 0; i < array.length; i++) {
        var line = '';
        for (var index in array[i]) {
            if (line != '') line += ','

            if (Array.isArray(array[i][index])){
                line += '"'+array[i][index]+'"'
            }else{
                line += array[i][index];
            }
        }

        str += line + '\r\n';
    }

    return str;
}

function exportCSVFile(csv, fileTitle) {
    var exportedFilenmae = fileTitle + '.csv' || 'export.csv';

    var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    if (navigator.msSaveBlob) { // IE 10+
        navigator.msSaveBlob(blob, exportedFilenmae);
    } else {
        var link = document.createElement("a");
        if (link.download !== undefined) { // feature detection
            // Browsers that support HTML5 download attribute
            var url = URL.createObjectURL(blob);
            link.setAttribute("href", url);
            link.setAttribute("download", exportedFilenmae);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }
}