/*global define*/
/*jslint white: true*/
define([
    'bluebird',
    'kb/common/html',
    'kb/service/client/workspace',
    'kb/service/client/userAndJobState',
    './lib/easyTree',
    'kb/service/utils',
    'kb/widget/bases/dataWidget'
], function (Promise, html, Workspace, UserAndJobState, EasyTree, serviceUtils, DataWidget) {
    'use strict';

    function makeObjectRef(obj) {
        return serviceUtils.makeWorkspaceObjectRef(obj.workspaceId, obj.objectId, obj.objectVersion);
    }


    function factory(config) {
        var defaultWidth = 1045,
            defaultHeight = 600;
        return DataWidget.make({
            runtime: config.runtime,
            title: 'Tree Data Viewy',
            on: {
                fetch: function () {
                    console.log('fetching...');
                    var workspaceClient = new Workspace(this.runtime.getConfig('services.workspace.url'), {
                        token: this.runtime.service('session').getAuthToken()
                    }),
                        ujsClient = new UserAndJobState(this.runtime.getConfig('services.ujs.url'), {
                            token: this.runtime.service('session').getAuthToken()
                        }),
                        ref = makeObjectRef(this.get('params')),
                        // these thread through and are build in the data api calls.
                        refList = [],
                        refToInfoMap = {};
                    
                    this.setTitle(html.loading('Loading Tree Data ...'));

                    return workspaceClient.get_objects([{ref: ref}])
                        .then(function (data) {
                            console.log('got objects');
                            if (data.length === 1) {
                                return data[0].data;
                            } else {
                                throw new Error('Invalid results');
                            }
                        })
                        .then(function (tree) {
                            // Build a list of references, then fetch the object info for them ...
                            if (tree.ws_refs) {
                                refList = Object.keys(tree.ws_refs).map(function (key) {
                                    return {ref: tree.ws_refs[key].g[0]};
                                });
                            }
                            console.log('HERE');
                            console.log(tree);
                            console.log(refList);
                            return Promise.all([tree, workspaceClient.get_object_info_new({objects: refList}).then(function (result) {
                                    console.log('GOT RESULT');
                                    console.log(result);
                                    return result;
                            }).catch(function (err) {
                                console.log('NEW ERROR'); console.log(err);
                            })]);
                        })
                        .spread(function (tree, objectInfoList) {
                            console.log('got object info');
                            // ... and then map them by their original ref.
                            var i;
                            for (i = 0; i < objectInfoList.length; i += 1) {
                                refToInfoMap[refList[i].ref] = serviceUtils.object_info_to_object(objectInfoList[i]);
                            }

                            console.log('setting data to ');
                            
                            var data = {
                                tree: tree,
                                refToInfoMap: refToInfoMap,
                            };
                            console.log(data);
                            this.set('data', {
                                tree: tree,
                                refToInfoMap: refToInfoMap,
                            });

                        }.bind(this));
                },
                /*
                 * as soon as possible, which should be right after attachment, 
                 * place this layout markup. Any specific places, which are nodes
                 * with ids, may be returned in the places property, and later
                 * accessed as getPlace('place').
                 * 
                 * Note: this is WITHIN the widget native layout.
                 */
                layout: function (container) {
                    console.log('in layout');
                    var containerId = html.genId(),
                        canvasId = html.genId(),
                        div = html.tag('div'),
                        canvas = html.tag('canvas'),
                        layout = div({id: containerId}, [
                            canvas({id: canvasId, style: {maxHeight: (config.height || defaultHeight) - 85, overflow: 'scroll'}})
                        ]);
                    return {
                        content: layout,
                        places: {
                            canvas: {
                                id: canvasId
                            }
                        }
                    };
                },
                render: function () {
                    console.log('in render');
                    var data = this.get('data'),
                        canvas = this.getPlace('canvas');
                    if (!data) {
                        return;
                    }
                    console.log(data);
                    this.setTitle('Tree Data Viewx');
                    new EasyTree(canvas.id, data.tree.tree, data.tree.default_node_labels,
                        function (node) {
                            var url;
                            if ((!data.tree.ws_refs || (!data.tree.ws_refs[node.id]))) {
                                var nodeName = data.tree.default_node_labels[node.id];
                                if (nodeName.indexOf('/') > 0) {
                                    url = '#genes/' + this.get('params').workspaceId + '/' + nodeName;
                                    console.log('URL1');
                                    console.log(url);
                                }
                                return;
                            }
                            console.log('HERE!!');
                            var ref = data.tree.ws_refs[node.id].g[0],
                                objectInfo = data.refToInfoMap[ref];
                            console.log(ref);
                            console.log(objectInfo);
                            if (objectInfo) {
                                // Either way works...
                                // url = '#dataview/' + objectInfo.wsid + '/' + objectInfo.id;
                                url = '#dataview/' + objectInfo.ws + '/' + objectInfo.name;
                                window.open(url, '_blank');
                            }
                        },
                        function (node) {
                            console.log('THERE!');
                            console.log(node);
                            if (node.id && node.id.indexOf('user') === 0) {
                                return '#0000ff';
                            }
                            return null;
                        });
                }
            }
        });
    }

    return {
        make: function (config) {
            return factory(config);
        }
    };
});
@@ -694,17 +694,16 @@
 ata View
-y
 ',%0A     
@@ -756,56 +756,8 @@
 ) %7B%0A
-                    console.log('fetching...');%0A
     
@@ -1052,18 +1052,29 @@
 rvices.u
-j
 s
+er_job_state
 .url'), 
@@ -1633,64 +1633,8 @@
 ) %7B%0A
-                            console.log('got objects');%0A
     
@@ -2325,154 +2325,8 @@
   %7D%0A
-                            console.log('HERE');%0A                            console.log(tree);%0A                            console.log(refList);%0A
     
@@ -2460,128 +2460,8 @@
 ) %7B%0A
-                                    console.log('GOT RESULT');%0A                                    console.log(result);%0A
     
@@ -2601,19 +2601,21 @@
 console.
-log
+error
 ('NEW ER
@@ -2621,24 +2621,57 @@
 RROR'); 
+%0A                                
 console.
 log(err)
@@ -2662,19 +2662,21 @@
 console.
-log
+error
 (err);%0A 
@@ -2805,68 +2805,8 @@
 ) %7B%0A
-                            console.log('got object info');%0A
     
@@ -3142,98 +3142,8 @@
  %7D%0A%0A
-                            console.log('setting data to ');%0A                            %0A
     
@@ -3318,55 +3318,8 @@
  %7D;%0A
-                            console.log(data);%0A
     
@@ -4024,54 +4024,8 @@
 ) %7B%0A
-                    console.log('in layout');%0A
     
@@ -4764,54 +4764,8 @@
 ) %7B%0A
-                    console.log('in render');%0A
     
@@ -4958,47 +4958,8 @@
   %7D%0A
-                    console.log(data);%0A
     
@@ -5003,17 +5003,16 @@
 ata View
-x
 ');%0A    
@@ -5525,119 +5525,8 @@
 me;%0A
-                                    console.log('URL1');%0A                                    console.log(url);%0A
     
@@ -5629,59 +5629,8 @@
   %7D%0A
-                            console.log('HERE!!');%0A
     
@@ -5769,107 +5769,8 @@
 f%5D;%0A
-                            console.log(ref);%0A                            console.log(objectInfo);%0A
     
@@ -6216,106 +6216,8 @@
 ) %7B%0A
-                            console.log('THERE!');%0A                            console.log(node);%0A
     

remove console logs