'use strict';
import Dom from 'metal-dom/src/dom';
import MultiMap from 'metal-structs/src/MultiMap'
import Datatable from 'metal-datatable/src/Datatable';
import Modal from 'metal-modal/src/Modal';
import Ajax from 'metal-ajax/src/Ajax';
import TreeView from 'metal-treeview/src/Treeview';

class FgTable {
	constructor(apiUrl = 'https://localhost/apis/v1.0 ', tableIdentifier='#application', token='') {
		this.apiUrl = apiUrl;
		this.tableIdentifier = tableIdentifier;
		this.token = token;
	}
	
	render (resource, columns, details_callback) {
	    if(this.token.substring(0,4) == 'User' || this.token.substring(0,7) == 'No JSON') {
	        Dom.append(this.tableIdentifier,'<h1 class="">No Token available.</h1>');
	        return;
	    }
	    
        var table_data = [{'col1':'test1', 'col2':'test2'},{'col1':'test3', 'col2':'test4'}];
        
        var headers = new MultiMap();
        headers.add('Authorization', 'Bearer ' + this.token);
        headers.add('content-type', 'application/json');
            
        var promise = Ajax.request(this.apiUrl+'/'+resource, 'GET',null, headers, null);
        var tableBlock = this.tableIdentifier;        
        promise.then(function(data){
            var tableData = JSON.parse(data.response)[resource];
            tableData.forEach(function(entry){
                Object.keys(entry).forEach(function(keyEntry){
                    if(columns.indexOf(keyEntry) < 0){
                        delete(entry[keyEntry]);
                    }
                    
                });
                columns.forEach(function(keyEntry){
                    if (keyEntry == 'id') {
                        entry[keyEntry] = '<a href="#' + entry[keyEntry] + '" onClick="'+ details_callback +'('+entry[keyEntry]+')">' + entry[keyEntry] + '</a>'; 
                    }
                    entry[keyEntry.capitalize()] = entry[keyEntry];
                    delete(entry[keyEntry]);
                });
            });
            var dt = new Datatable({'data': tableData, displayColumnsType: false, formatColumns: unsortColumns}, tableBlock);
        });
	}

	showDetails(resource, id) {
        if(this.token.substring(0,4) == 'User' || this.token.substring(0,7) == 'No JSON') {
            var modalError = new Modal({
                elementClasses: 'modal-boot',
                header: '<h4 class="modal-title">Error</h4>',
                body: 'No token available!',
                footer: '<button type="button" class="btn btn-primary">OK</button>'
            });
            modalError.show();
            return;
        }
        var headers = new MultiMap();
        headers.add('Authorization', 'Bearer ' + this.token);
        headers.add('content-type', 'application/json');
            
        var promise = Ajax.request(this.apiUrl + '/' + resource + '/' + id, 'GET', null, headers, null);
        promise.then(function(data){
            var modalTask = new Modal({
                elementClasses: 'modal-boot',
                header: '<h4 class="modal-title">Task: ' + id + '</h4>',
                body: '<div id="' + resource + id + '"></div>'
            });

            var ciccio = FgTable.convertToNodes(JSON.parse(data.response));
            new TreeView({
                nodes: FgTable.convertToNodes(JSON.parse(data.response))
            }, '#' + resource + id);
            
            modalTask.show();
            
        });
	}
	
	static convertToNodes(json) {
	    var nodes = new Array();
	    var childrenList;
	    Object.keys(json).forEach(function(key){
            if(typeof json[key] !== null && typeof json[key] === 'object'){
                if(Array.isArray(json[key])){
                    childrenList = new Array();
                    json[key].forEach(function(childElem){
                        if(typeof childElem !== null && typeof childElem === 'object'){
                            childrenList.push({name: childElem, children: FgTable.convertToNodes(childElem)});
                        } else {
                            childrenList.push({name: childElem});
                        }
                    });
                    if(childrenList.length>0){
                        nodes.push({name: key, children: childrenList});
                    } else {
                        nodes.push({name: key, children: [{name: 'N/A'}]});
                    }
                } else {
                    nodes.push({name: key, children: FgTable.convertToNodes(json[key])});
                }
            } else {
                nodes.push({name: key, children: [{name: json[key]}]});
            }
	    });
	    return nodes;
    }
}

function unsortColumns(columns) {
    return columns
}

String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

export default FgTable;
@@ -354,16 +354,25 @@
 /v1.0 ',
+%0A%09       
  tableId
@@ -2899,32 +2899,128 @@
 function(data)%7B%0A
+            var date = new Date();%0A            var resourceId = resource + id + date.getTime();%0A
             var 
@@ -3202,28 +3202,25 @@
 ' + resource
- + i
+I
 d + '%22%3E%3C/div
@@ -3243,84 +3243,8 @@
 );%0A%0A
-            var ciccio = FgTable.convertToNodes(JSON.parse(data.response));%0A
     
@@ -3368,20 +3368,17 @@
 resource
- + i
+I
 d);%0A    
@@ -3742,24 +3742,63 @@
 ew Array();%0A
+                    var arrayElem = 0;%0A
             
@@ -3985,25 +3985,27 @@
 (%7Bname: 
-child
+array
 Elem
+++
 , childr

Fix the multiple detail open modal