PageRenderTime 160ms CodeModel.GetById 76ms app.highlight 75ms RepoModel.GetById 1ms app.codeStats 0ms

/v3.2/nimbits-tds/src/com/nimbits/client/panels/NavigationPanel.java

http://nimbits-server.googlecode.com/
Java | 988 lines | 826 code | 131 blank | 31 comment | 117 complexity | da1b10c22b0839d0f958cb23a542ac77 MD5 | raw file
  1/*
  2 * Copyright (c) 2010 Tonic Solutions LLC.
  3 *
  4 * http://www.nimbits.com
  5 *
  6 *
  7 * Licensed under the GNU GENERAL PUBLIC LICENSE, Version 3.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
  8 *
  9 * http://www.gnu.org/licenses/gpl.html
 10 *
 11 * Unless required by applicable law or agreed to in writing, software distributed under the license is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 12 */
 13
 14package com.nimbits.client.panels;
 15
 16import com.extjs.gxt.ui.client.Style.Scroll;
 17import com.extjs.gxt.ui.client.data.ModelData;
 18import com.extjs.gxt.ui.client.data.ModelIconProvider;
 19import com.extjs.gxt.ui.client.dnd.DND.Feedback;
 20import com.extjs.gxt.ui.client.dnd.TreePanelDragSource;
 21import com.extjs.gxt.ui.client.dnd.TreePanelDropTarget;
 22import com.extjs.gxt.ui.client.event.*;
 23import com.extjs.gxt.ui.client.store.TreeStore;
 24import com.extjs.gxt.ui.client.util.Format;
 25import com.extjs.gxt.ui.client.util.Params;
 26import com.extjs.gxt.ui.client.widget.ContentPanel;
 27import com.extjs.gxt.ui.client.widget.Info;
 28import com.extjs.gxt.ui.client.widget.MessageBox;
 29import com.extjs.gxt.ui.client.widget.Window;
 30import com.extjs.gxt.ui.client.widget.button.Button;
 31import com.extjs.gxt.ui.client.widget.menu.Menu;
 32import com.extjs.gxt.ui.client.widget.menu.MenuItem;
 33import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
 34import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
 35import com.google.gwt.core.client.GWT;
 36import com.google.gwt.user.client.Timer;
 37import com.google.gwt.user.client.rpc.AsyncCallback;
 38import com.google.gwt.user.client.ui.AbstractImagePrototype;
 39import com.nimbits.client.exception.NimbitsException;
 40import com.nimbits.client.exceptions.PointExistsException;
 41import com.nimbits.client.icons.Icons;
 42import com.nimbits.client.model.*;
 43import com.nimbits.client.model.category.Category;
 44import com.nimbits.client.model.category.CategoryName;
 45import com.nimbits.client.model.common.CommonFactoryLocator;
 46import com.nimbits.client.model.diagram.Diagram;
 47import com.nimbits.client.model.diagram.DiagramName;
 48import com.nimbits.client.model.email.EmailAddress;
 49import com.nimbits.client.model.point.Point;
 50import com.nimbits.client.model.point.PointName;
 51import com.nimbits.client.service.category.CategoryService;
 52import com.nimbits.client.service.category.CategoryServiceAsync;
 53import com.nimbits.client.service.datapoints.PointService;
 54import com.nimbits.client.service.datapoints.PointServiceAsync;
 55import com.nimbits.client.service.diagram.DiagramService;
 56import com.nimbits.client.service.diagram.DiagramServiceAsync;
 57import com.nimbits.shared.Utils;
 58
 59import java.util.HashMap;
 60import java.util.List;
 61import java.util.Map;
 62
 63
 64class NavigationPanel extends NavigationEventProvider {
 65    private final ContentPanel mainPanel;
 66    private GxtDiagramModel diagramModelToDelete;
 67    private GxtPointCategoryModel categoryModelToDelete;
 68    private GxtPointModel pointModelToDelete;
 69    private final Map<PointName, Point> pointMap = new HashMap<PointName, Point>();
 70    private final Map<CategoryName, Category> categoryMap = new HashMap<CategoryName, Category>();
 71    private final Map<DiagramName, Diagram> diagramMap = new HashMap<DiagramName, Diagram>();
 72    private Point pointToBeCopied;
 73
 74    private TreePanel<ModelData> tree;
 75    private TreeStore<ModelData> store;
 76    private final boolean isConnectionPanel;
 77    private final EmailAddress email;
 78
 79
 80    public NavigationPanel(final EmailAddress anEmailAddress, final boolean isConnection) {
 81        mainPanel = new ContentPanel();
 82        mainPanel.setHeaderVisible(false);
 83        mainPanel.setFrame(false);
 84        mainPanel.setBodyBorder(false);
 85        mainPanel.setHeight("100%");
 86        mainPanel.setScrollMode(Scroll.AUTOY);
 87
 88        this.isConnectionPanel = isConnection;
 89        this.email = anEmailAddress;
 90
 91        try {
 92            if (isConnectionPanel) {
 93                mainPanel.setHeight(600);
 94                loadConnectionTree();
 95            } else {
 96                mainPanel.setTopComponent(treeToolBar());
 97                loadAuthTree();
 98            }
 99        } catch (NimbitsException e) {
100            GWT.log(e.getMessage(), e);
101        }
102
103    }
104
105    private ToolBar treeToolBar() {
106        final ToolBar toolBar = new ToolBar();
107
108        toolBar.add(addNewCategoryButton());
109
110        toolBar.add(addNewPointButton());
111
112        toolBar.add(addNewDiagramButton());
113
114        return toolBar;
115    }
116
117    private Button addNewCategoryButton() {
118        final Button newCategory = new Button();
119        newCategory.setIcon(AbstractImagePrototype.create(Icons.INSTANCE.category()));
120        newCategory.setToolTip(Const.MESSAGE_ADD_CATEGORY);
121        newCategory.addListener(Events.OnClick, new Listener<BaseEvent>() {
122            @Override
123            public void handleEvent(final BaseEvent be) {
124                final MessageBox box = MessageBox.prompt(Const.MESSAGE_NEW_CATEGORY,
125                        Const.MESSAGE_NEW_CATEGORY_PROMPT);
126                box.addCallback(new Listener<MessageBoxEvent>() {
127                    @Override
128                    public void handleEvent(final MessageBoxEvent be) {
129                        final String newCategoryName = be.getValue();
130                        final CategoryName categoryName = CommonFactoryLocator.getInstance().createCategoryName(newCategoryName);
131
132                        final CategoryServiceAsync categoryService = GWT.create(CategoryService.class);
133                        try {
134                            categoryService.addCategory(categoryName,
135                                    new AsyncCallback<Category>() {
136                                        @Override
137                                        public void onFailure(Throwable caught) {
138                                            Info.display(Const.WORD_ERROR,
139                                                    caught.getMessage());
140                                        }
141
142                                        @Override
143                                        public void onSuccess(final Category c) {
144                                            final GxtPointCategoryModel m = new GxtPointCategoryModel(c);// PointCategoryModelFactory.createPointCategoryModel(c);
145                                            categoryMap.put(c.getName(), c);
146
147                                            if (store != null) {
148                                                store = tree.getStore();
149                                                store.add(m, true);
150
151                                                tree.setExpanded(m, true);
152                                                final String v = Format.ellipse(
153                                                        newCategoryName, 80);
154                                                Info.display(Const.WORD_SUCCESS,
155                                                        "New Category added: '{0}'",
156                                                        new Params(v));
157                                                layout(true);
158                                                try {
159                                                    if (!isConnectionPanel) {
160                                                        loadAuthTree();
161                                                    } else {
162                                                        loadConnectionTree();
163                                                    }
164                                                } catch (NimbitsException ignored) {
165                                                }
166                                            } else {
167                                                try {
168                                                    loadAuthTree();
169                                                } catch (NimbitsException e) {
170                                                    Info.display(Const.WORD_ERROR, e.getMessage());
171                                                }
172                                            }
173                                        }
174                                    });
175                        } catch (NimbitsException e) {
176                            Info.display(Const.WORD_ERROR, e.getMessage());
177                        }
178                    }
179                });
180            }
181        });
182        return newCategory;
183    }
184
185    private void loadConnectionTree() throws NimbitsException {
186
187
188        removeAll();
189
190        //add(statusImage());
191        final CategoryServiceAsync categoryService = GWT.create(CategoryService.class);
192        categoryService.getConnectionCategories(true, true, email,
193                new AsyncCallback<List<Category>>() {
194                    @Override
195                    public void onFailure(Throwable caught) {
196
197                        GWT.log(caught.getMessage(), caught);
198
199                    }
200
201                    @Override
202                    public void onSuccess(List<Category> result) {
203                        decideWhatViewToLoad(result);
204                    }
205                });
206    }
207
208    private void decideWhatViewToLoad(final List<Category> result) {
209        if (result.size() == 1) {
210            if (result.get(0).getDiagrams().size() == 0 && result.get(0).getPoints().size() == 0) {
211                showEmptyView();
212            } else {
213                createTree(result);
214            }
215        } else if (result.size() == 0) {
216            showEmptyView();
217        } else {
218            createTree(result);
219        }
220        setVisible(true);
221        add(mainPanel);
222        doLayout();
223    }
224
225    private void showEmptyView() {
226        if (this.isConnectionPanel) {
227            mainPanel.addText(Const.RESPONSE_NO_POINTS);
228        } else {
229            mainPanel.setUrl(Const.PATH_WELCOME_URL);
230        }
231        store = null;
232    }
233
234    private void createTree(final List<Category> result) {
235        store = new TreeStore<ModelData>();
236
237        tree = new TreePanel<ModelData>(store) {
238            @Override
239            protected boolean hasChildren(ModelData model) {
240                return model instanceof GxtPointCategoryModel || !(model instanceof GxtPointModel) && super.hasChildren(model);
241            }
242        };
243
244        treePropertyBuilder();
245        treeStoreBuilder(result);
246        setBorders(false);
247        setScrollMode(Scroll.AUTOY);
248        treeDNDBuilder();
249        final TreePanelDropTarget target = new TreePanelDropTarget(tree);
250        target.setAllowSelfAsSource(!isConnectionPanel);
251        target.setFeedback(Feedback.BOTH);
252        mainPanel.removeAll();
253        if (this.email != null && isConnectionPanel) {
254            mainPanel.addText(email.getValue());
255        }
256        mainPanel.add(tree);
257        doLayout(true);
258
259    }
260
261    private void treePropertyBuilder() {
262        if (!isConnectionPanel) {
263            tree.setContextMenu(createContextMenu());
264        }
265        tree.setStateful(true);
266        tree.setDisplayProperty(Const.PARAM_NAME);
267        tree.setTrackMouseOver(true);
268        tree.setHeight("100%");
269        tree.setIconProvider(new ModelIconProvider<ModelData>() {
270            @Override
271            public AbstractImagePrototype getIcon(ModelData model) {
272                // if (model.getInstance("icon") != null) {
273
274
275                if (model instanceof GxtPointCategoryModel) {
276                    return AbstractImagePrototype.create(Icons.INSTANCE.category());
277                } else if (model instanceof GxtPointModel) {
278                    switch (((GxtPointModel) model).getAlertState()) {
279                        case IdleAlert:
280                            return AbstractImagePrototype.create(Icons.INSTANCE.point_idle());
281                        case HighAlert:
282                            return AbstractImagePrototype.create(Icons.INSTANCE.point_high());
283                        case LowAlert:
284                            return AbstractImagePrototype.create(Icons.INSTANCE.point_low());
285                        default:
286                            return AbstractImagePrototype.create(Icons.INSTANCE.point_ok());
287                    }
288                } else if (model instanceof GxtDiagramModel) {
289                    return AbstractImagePrototype.create(Icons.INSTANCE.diagram());
290                } else {
291                    return null;
292                }
293                // return IconHelper.createStyle((String)
294                // model.getInstance("icon"));
295                // } else {
296                ////     return null;
297                // }
298            }
299        });
300
301
302        tree.addListener(Events.OnDoubleClick,
303                new Listener<TreePanelEvent<ModelData>>() {
304                    @Override
305                    public void handleEvent(TreePanelEvent<ModelData> be) {
306                        ModelData selectedFolder = tree.getSelectionModel()
307                                .getSelectedItem();
308
309                        if (selectedFolder != null) {
310                            // String icon = selectedFolder.getInstance("icon");
311
312                            if (selectedFolder instanceof GxtPointCategoryModel) {
313                                try {
314
315
316                                    Category category = categoryMap.get(((GxtPointCategoryModel) selectedFolder).getName());
317
318                                    notifyCategoryClickedListener(category, isConnectionPanel);
319                                } catch (NimbitsException e) {
320                                    GWT.log(e.getMessage(), e);
321                                }
322                            } else if (selectedFolder instanceof GxtPointModel) {
323                                Point point = pointMap.get(((GxtPointModel) selectedFolder).getName());
324                                point.setReadOnly(isConnectionPanel);
325                                point.setClientType(ClientType.other);
326                                notifyPointClickedListener(point);
327                            } else if (selectedFolder instanceof GxtDiagramModel) {
328                                Diagram diagram = diagramMap.get(((GxtDiagramModel) selectedFolder).getName());
329                                diagram.setClientType(ClientType.other);
330                                diagram.setReadOnly(isConnectionPanel);
331                                notifyDiagramClickedListener(diagram);
332                            }
333                        } else {
334                            try {
335                                loadAuthTree();
336                            } catch (NimbitsException ignored) {
337                            }
338                        }
339                    }
340                });
341    }
342
343    private Menu createContextMenu() {
344        Menu contextMenu = new Menu();
345
346        contextMenu.add(propertyContext());
347        contextMenu.add(copyContext());
348        contextMenu.add(deleteContext());
349        return contextMenu;
350    }
351
352    private MenuItem copyContext() {
353        MenuItem retObj = new MenuItem();
354        retObj.setText("Copy");
355        retObj.setIcon(AbstractImagePrototype.create(Icons.INSTANCE.album()));
356        retObj.addSelectionListener(new SelectionListener<MenuEvent>() {
357            public void componentSelected(MenuEvent ce) {
358                ModelData selectedModel = tree.getSelectionModel().getSelectedItem();
359
360                if (selectedModel.get(Const.PARAM_ICON).equals(Const.PARAM_POINT)) {
361                    GxtPointModel model = (GxtPointModel) selectedModel;
362                    pointToBeCopied = pointMap.get(model.getName());
363                    final MessageBox box = MessageBox.prompt(
364                            Const.MESSAGE_NEW_POINT,
365                            Const.MESSAGE_NEW_POINT_PROMPT);
366                    box.addCallback(copyPointListener());
367                }
368            }
369        });
370        return retObj;
371    }
372
373    private Listener<MessageBoxEvent> copyPointListener() {
374        return new Listener<MessageBoxEvent>() {
375            private String newPointName;
376
377            @Override
378            public void handleEvent(MessageBoxEvent be) {
379                newPointName = be.getValue();
380                if (!Utils.isEmptyString(newPointName)) {
381                    final MessageBox box = MessageBox.wait("Progress",
382                            "Creating your data point channel into the cloud", "Creating: " + newPointName);
383                    box.show();
384                    PointServiceAsync pointService = GWT.create(PointService.class);
385
386
387                    PointName pointName = CommonFactoryLocator.getInstance().createPointName(newPointName);
388
389                    pointService.copyPoint(pointToBeCopied, pointName,
390                            new AsyncCallback<Point>() {
391                                @Override
392                                public void onFailure(Throwable caught) {
393                                    Info.display("Could not create "
394                                            + newPointName,
395                                            caught.getMessage());
396                                    box.close();
397                                }
398
399                                @Override
400                                public void onSuccess(Point result) {
401                                    try {
402                                        reloadTree();
403                                    } catch (NimbitsException e) {
404                                        GWT.log(e.getMessage(), e);
405                                    }
406                                    box.close();
407                                }
408                            });
409                }
410            }
411        };
412    }
413
414    private void reloadTree() throws NimbitsException {
415        if (isConnectionPanel) {
416            try {
417                loadConnectionTree();
418            } catch (NimbitsException ignored) {
419            }
420        } else {
421            loadAuthTree();
422        }
423    }
424
425    private MenuItem deleteContext() {
426        MenuItem retObj = new MenuItem();
427
428
429        retObj.setText("Delete");
430        retObj.setIcon(AbstractImagePrototype.create(Icons.INSTANCE.delete()));
431        retObj.addSelectionListener(new SelectionListener<MenuEvent>() {
432            public void componentSelected(MenuEvent ce) {
433                ModelData selectedModel = tree.getSelectionModel().getSelectedItem();
434                if (selectedModel.get(Const.PARAM_ICON).equals(Const.PARAM_CATEGORY)) {
435                    categoryModelToDelete = (GxtPointCategoryModel) selectedModel;
436
437                    MessageBox.confirm("Confirm", "Are you sure you want delete this category? Doing so will permanently delete all of the points in this category along with their date"
438                            , deleteCategoryListener);
439                } else if (selectedModel.get(Const.PARAM_ICON).equals(Const.PARAM_POINT)) {
440                    pointModelToDelete = (GxtPointModel) selectedModel;
441
442                    MessageBox.confirm("Confirm", "Are you sure you want delete this Point? Doing so will permanently delete all of its historical data"
443                            , deletePointListener);
444                } else if (selectedModel.get(Const.PARAM_ICON).equals(Const.PARAM_DIAGRAM)) {
445                    diagramModelToDelete = (GxtDiagramModel) selectedModel;
446
447                    MessageBox.confirm("Confirm", "Are you sure you want delete this Diagram?"
448                            , deleteDiagramListener);
449                }
450            }
451        });
452        return retObj;
453    }
454
455    private MenuItem propertyContext() {
456        MenuItem retObj = new MenuItem();
457
458
459        retObj.setText(Const.WORD_PROPERTIES);
460        retObj.setIcon(AbstractImagePrototype.create(Icons.INSTANCE.edit()));
461        retObj.addSelectionListener(new SelectionListener<MenuEvent>() {
462            public void componentSelected(MenuEvent ce) {
463                ModelData selectedModel = tree.getSelectionModel().getSelectedItem();
464                if (selectedModel.get(Const.PARAM_ICON).equals(Const.PARAM_CATEGORY)) {
465
466                } else if (selectedModel.get(Const.PARAM_ICON).equals(Const.PARAM_POINT)) {
467
468                    GxtPointModel model = ((GxtPointModel) selectedModel);
469                    Point p = pointMap.get(model.getName());
470                    try {
471                        createPointPropertyWindow(p);
472                    } catch (NimbitsException e) {
473                        GWT.log(e.getMessage());
474                    }
475
476
477                } else if (selectedModel.get(Const.PARAM_ICON).equals(Const.PARAM_DIAGRAM)) {
478                    GxtDiagramModel diagramModel = (GxtDiagramModel) selectedModel;
479                    Diagram diagram = diagramMap.get(diagramModel.getName());
480
481                    DiagramPropertyPanel dp = new DiagramPropertyPanel(diagram, diagram.isReadOnly());
482                    final Window w = new Window();
483                    w.setWidth(500);
484                    w.setHeight(400);
485                    w.setHeading(diagram.getName() + " " + Const.WORD_PROPERTIES);
486                    w.add(dp);
487                    w.show();
488                }
489            }
490        });
491        return retObj;
492    }
493
494    private void createPointPropertyWindow(Point p) throws NimbitsException {
495        final com.extjs.gxt.ui.client.widget.Window window = new com.extjs.gxt.ui.client.widget.Window();
496        final PointPanel pp = new PointPanel(p);
497
498        pp.addPointUpdatedListeners(new PointPanel.PointUpdatedListener() {
499            @Override
500            public void onPointUpdated(Point p) {
501                pointMap.remove(p.getName());
502                pointMap.put(p.getName(), p);
503                // points.remove(p.getName());
504                // points.put(p.getName(), p) ;
505
506                //	mp.setTopComponent(mainToolBar( points));
507            }
508        });
509
510        pp.addPointDeletedListeners(new PointPanel.PointDeletedListener() {
511            @Override
512            public void onPointDeleted(Point p) {
513                pointMap.remove(p.getName());
514
515
516            }
517        });
518
519        window.setIcon(AbstractImagePrototype.create(Icons.INSTANCE.connect()));
520        window.setSize(466, 520);
521        window.setPlain(false);
522        window.setModal(true);
523        window.setBlinkModal(true);
524        window.setHeading(p.getName().getValue() + " Properties");
525        window.setHeaderVisible(true);
526        window.setBodyBorder(true);
527//	window.setLayout(new FitLayout());
528        window.add(pp);
529        window.show();
530    }
531
532    private void treeStoreBuilder(final List<Category> result) {
533        pointMap.clear();
534        diagramMap.clear();
535        categoryMap.clear();
536
537
538        for (Category c : result) {
539            GxtPointCategoryModel gxtPointCategoryModel = new GxtPointCategoryModel(c);//  PointCategoryModelFactory.createPointCategoryModel(c);
540
541            if (!categoryMap.containsKey(c.getName())) {
542                categoryMap.put(c.getName(), c);
543            }
544            if (!c.getName().getValue().equals(Const.CONST_HIDDEN_CATEGORY)) {
545                if (!(c.getPoints() == null)) {
546                    for (Point p : c.getPoints()) {
547                        if (!pointMap.containsKey(p.getName())) {
548                            pointMap.put(p.getName(), p);
549                        }
550                        p.setCatID(c.getId());
551                        gxtPointCategoryModel.add(new GxtPointModel(p));
552                    }
553                }
554                if (!(c.getDiagrams() == null)) {
555                    for (Diagram d : c.getDiagrams()) {
556                        if (!diagramMap.containsKey(d.getName())) {
557                            diagramMap.put(d.getName(), d);
558                        }
559                        d.setCategoryFk(c.getId());
560                        gxtPointCategoryModel.add(new GxtDiagramModel(d));
561                    }
562                }
563                store.add(gxtPointCategoryModel, true);
564            }
565        }
566
567        for (Category c : result) {
568            if (c.getName().getValue().equals(Const.CONST_HIDDEN_CATEGORY) && (c.getPoints() != null)) {
569                for (Point p : c.getPoints()) {
570                    if (!pointMap.containsKey(p.getName())) {
571                        pointMap.put(p.getName(), p);
572                        p.setCatID(c.getId());
573                        store.add(new GxtPointModel(p), false);
574                    }
575                    //  break;
576                }
577                if (c.getName().getValue().equals(Const.CONST_HIDDEN_CATEGORY) && (c.getDiagrams() != null)) {
578                    for (Diagram d : c.getDiagrams()) {
579                        if (!diagramMap.containsKey(d.getName())) {
580                            diagramMap.put(d.getName(), d);
581                        }
582                        d.setCategoryFk(c.getId());
583                        store.add(new GxtDiagramModel(d), false);
584                    }
585                    //  break;
586                }
587            }
588        }
589    }
590
591    private void treeDNDBuilder() {
592        TreePanelDragSource source = new TreePanelDragSource(tree);
593        source.addDNDListener(new DNDListener() {
594            ModelData selectedModel;
595
596            @Override
597            public void dragStart(DNDEvent e) {
598                super.dragStart(e);
599                selectedModel = tree.getSelectionModel().getSelectedItem();
600
601                if (selectedModel != null && selectedModel == tree.getStore().getRootItems().get(0)) {
602                    e.setCancelled(true);
603                    e.getStatus().setStatus(false);
604                } else if (selectedModel != null) {
605                    if (selectedModel.get(Const.PARAM_ICON).equals(Const.PARAM_CATEGORY)) {
606                        e.setCancelled(true);
607                        e.getStatus().setStatus(false);
608                    }
609                }
610            }
611
612            @Override
613            public void dragDrop(final DNDEvent e) {
614                super.dragDrop(e);
615
616                if (!(e.getTarget().getInnerHTML().equals("&nbsp;")) && !isConnectionPanel) {
617                    if (selectedModel instanceof GxtPointModel) {
618                        final GxtPointModel gxtPointModel = (GxtPointModel) selectedModel;
619                        selectedModel.set(Const.PARAM_NAME, gxtPointModel.getName().getValue());
620
621                        PointServiceAsync pointService = GWT.create(PointService.class);
622                        try {
623                            CategoryName categoryName = CommonFactoryLocator.getInstance().createCategoryName(e.getTarget()
624                                    .getInnerText());
625                            pointService.movePoint(gxtPointModel.getName(), categoryName, new AsyncCallback<Point>() {
626                                @Override
627                                public void onFailure(Throwable caught) {
628                                    Info.display(Const.WORD_ERROR, caught.getMessage());
629                                }
630
631                                @Override
632                                public void onSuccess(Point result) {
633                                    // System.out.println();
634                                    Info.display("Point moved ", gxtPointModel.getName().getValue());
635                                }
636                            });
637                        } catch (NimbitsException e1) {
638                            Info.display(Const.WORD_ERROR, e1.getMessage());
639                        }
640                    } else if (selectedModel instanceof GxtDiagramModel) {
641                        final GxtDiagramModel gxtDiagramModel = (GxtDiagramModel) selectedModel;
642
643                        selectedModel.set(Const.PARAM_NAME, gxtDiagramModel.getName());
644
645                        DiagramServiceAsync diagramService = GWT.create(DiagramService.class);
646                        try {
647                            CategoryName categoryName = CommonFactoryLocator.getInstance().createCategoryName(e.getTarget().getInnerText());
648                            diagramService.moveDiagram(gxtDiagramModel.getName(), categoryName, new AsyncCallback<Void>() {
649
650                                @Override
651                                public void onFailure(Throwable throwable) {
652
653                                }
654
655                                @Override
656                                public void onSuccess(Void aVoid) {
657                                    try {
658                                        loadAuthTree();
659                                    } catch (NimbitsException e1) {
660                                        GWT.log(e1.getMessage(), e1);
661                                    }
662                                }
663                            });
664                        } catch (NimbitsException caught) {
665                            Info.display(Const.WORD_ERROR, caught.getMessage());
666                        }
667                    }
668                } else {
669                    // final GxtPointModel gxtPointModel = (GxtPointModel) selectedModel;
670                    // store.add(gxtPointModel, true);
671
672                    try {
673                        if (!isConnectionPanel) {
674                            loadAuthTree();
675                        } else {
676                            loadConnectionTree();
677                        }
678                    } catch (NimbitsException ignored) {
679                    }
680                }
681            }
682        });
683    }
684
685    private void loadAuthTree() throws NimbitsException {
686
687        removeAll();
688
689        //	add(statusImage());
690        final CategoryServiceAsync categoryService = GWT.create(CategoryService.class);
691        categoryService.getCategories(true, true, true,
692                new AsyncCallback<List<Category>>() {
693                    @Override
694                    public void onFailure(Throwable caught) {
695                        GWT.log(caught.getMessage(), caught);
696                    }
697
698                    @Override
699                    public void onSuccess(List<Category> result) {
700                        decideWhatViewToLoad(result);
701                    }
702                });
703    }
704
705    private Button addNewPointButton() {
706        Button newPoint = new Button("");
707        newPoint.setIcon(AbstractImagePrototype.create(Icons.INSTANCE.point_ok()));
708        newPoint.setToolTip(Const.MESSAGE_NEW_POINT);
709
710        newPoint.addListener(Events.OnClick, new Listener<BaseEvent>() {
711            @Override
712            public void handleEvent(BaseEvent be) {
713                final MessageBox box = MessageBox.prompt(
714                        Const.MESSAGE_NEW_POINT,
715                        Const.MESSAGE_NEW_POINT_PROMPT);
716                box.addCallback(createNewPointListener());
717            }
718
719            private Listener<MessageBoxEvent> createNewPointListener() {
720                return new Listener<MessageBoxEvent>() {
721                    private String newPointName;
722
723                    @Override
724                    public void handleEvent(MessageBoxEvent be) {
725                        newPointName = be.getValue();
726                        if (!Utils.isEmptyString(newPointName)) {
727                            final MessageBox box = MessageBox.wait("Progress",
728                                    "Creating your data point channel into the cloud", "Creating: " + newPointName);
729                            box.show();
730                            PointServiceAsync pointService = GWT.create(PointService.class);
731
732
733                            PointName pointName = CommonFactoryLocator.getInstance().createPointName(newPointName);
734
735                            try {
736                                pointService.addPoint(pointName, new AsyncCallback<Point>() {
737                                    @Override
738                                    public void onFailure(Throwable caught) {
739                                        Info.display("Could not create "
740                                                + newPointName,
741                                                caught.getMessage());
742                                        box.close();
743                                    }
744
745                                    @Override
746                                    public void onSuccess(Point result) {
747                                        addNewlyCreatedPointToTree(result);
748                                        box.close();
749                                    }
750                                });
751                            } catch (NimbitsException e) {
752                                box.close();
753                                GWT.log(e.getMessage());
754                            } catch (PointExistsException e) {
755                                box.close();
756                                Info.display("Could not create "
757                                        + newPointName,
758                                        e.getMessage());
759                            }
760                        }
761                    }
762                };
763            }
764        });
765        return newPoint;
766    }
767
768    private void addNewlyCreatedPointToTree(final Point result) {
769        pointMap.put(result.getName(), result);
770        if (tree != null && tree.getStore() != null) {
771            GxtPointModel model = new GxtPointModel(result);
772            store = tree.getStore();
773            store.add(model, true);
774            tree.setExpanded(model, true);
775
776        } else {
777            try {
778                loadAuthTree();
779            } catch (NimbitsException e) {
780                Info.display(Const.WORD_ERROR, e.getMessage());
781            }
782        }
783    }
784
785    private Button addNewDiagramButton() {
786        Button newDiagram = new Button();
787        newDiagram.setIcon(AbstractImagePrototype.create(Icons.INSTANCE.diagram()));
788        newDiagram.setToolTip("Add a new process diagram");
789
790        newDiagram.addListener(Events.OnClick, addDiagramListener());
791        return newDiagram;
792    }
793
794    private Listener<BaseEvent> addDiagramListener() {
795        return new Listener<BaseEvent>() {
796            @Override
797            public void handleEvent(final BaseEvent be) {
798                final Window w = new Window();
799                w.setAutoWidth(true);
800                w.setHeading(Const.MESSAGE_UPLOAD_SVG);
801                DiagramUploadPanel p = new DiagramUploadPanel(DiagramUploadPanel.UploadType.newFile);
802                p.addDiagramAddedListeners(new DiagramUploadPanel.DiagramAddedListener() {
803                    @Override
804                    public void onDiagramAdded() throws NimbitsException {
805                        w.hide();
806                        reloadTree();
807                    }
808                });
809
810                w.add(p);
811                w.show();
812            }
813        };
814    }
815
816    @Override
817    protected void afterRender() {
818        super.afterRender();
819        layout(true);
820    }
821
822    @Override
823    protected void onAttach() {
824        final Timer updater = new Timer() {
825            @Override
826            public void run() {
827                try {
828                    updateValues();
829                } catch (NimbitsException e) {
830                    GWT.log(e.getMessage(), e);
831                }
832            }
833        };
834        // updater.schedule(1000);
835        updater.scheduleRepeating(Const.DEFAULT_TIMER_UPDATE_SPEED);
836        updater.run();
837        super.onAttach();
838    }
839
840    private void updateValues() throws NimbitsException {
841        if (tree != null) {
842            final CategoryServiceAsync service = GWT.create(CategoryService.class);
843            service.getCategories(true, false, true, new AsyncCallback<List<Category>>() {
844                @Override
845                public void onFailure(final Throwable throwable) {
846                    GWT.log(throwable.getMessage(), throwable);
847                }
848
849                @Override
850                public void onSuccess(final List<Category> categories) {
851                    final TreeStore<ModelData> models = tree.getStore();
852                    final HashMap<PointName, Point> pointHashMap = new HashMap<PointName, Point>();
853
854                    for (final Category c : categories) {
855                        if (c.getPoints() != null) {
856                            for (final Point p : c.getPoints()) {
857                                if (p.isHighAlarmOn() || p.isLowAlarmOn() || p.isIdleAlarmOn()) {
858                                    pointHashMap.put(p.getName(), p);
859                                }
860                            }
861                        }
862                    }
863
864                    for (final ModelData m : models.getAllItems()) {
865                        if (m instanceof GxtPointModel) {
866                            final GxtPointModel gxtPointModel = (GxtPointModel) m;
867                            if (pointHashMap.containsKey(((GxtPointModel) m).getName())) {
868                                gxtPointModel.setAlertState(pointHashMap.get(gxtPointModel.getName()).getAlertState());
869                            }
870                            models.update(m);
871                        }
872                    }
873                }
874            });
875        }
876    }
877
878    public void addPoint(final Point p, final Category c) {
879        store = tree.getStore();
880        c.getPoints().add(p);
881        GxtPointCategoryModel model = new GxtPointCategoryModel(c);
882        GxtPointModel pModel = new GxtPointModel(p);
883        store.remove(model);
884        model.add(pModel);
885        store.add(model, true);
886        if (!pointMap.containsKey(p.getName())) {
887            pointMap.put(p.getName(), p);
888        }
889        if (!categoryMap.containsKey(c.getName())) {
890            categoryMap.put(c.getName(), c);
891        }
892        tree.setExpanded(model, true);
893    }
894
895    private final Listener<MessageBoxEvent> deleteCategoryListener = new Listener<MessageBoxEvent>() {
896        public void handleEvent(MessageBoxEvent ce) {
897            Button btn = ce.getButtonClicked();
898            final CategoryServiceAsync categoryService = GWT.create(CategoryService.class);
899
900            if (btn.getText().equals(Const.WORD_YES)) {
901                Category categoryToDelete = categoryMap.get(categoryModelToDelete.getName());
902                categoryService.deleteCategory(categoryToDelete, new AsyncCallback<Void>() {
903                    @Override
904                    public void onFailure(Throwable e) {
905                        GWT.log(e.getMessage(), e);
906                    }
907
908                    @Override
909                    public void onSuccess(Void aVoid) {
910                        for (ModelData modelData : categoryModelToDelete.getChildren()) {
911                            GxtPointModel pointModel = (GxtPointModel) modelData;
912                            Point point = pointMap.get(pointModel.getName());
913                            try {
914                                notifyPointDeletedListener(point);
915                            } catch (NimbitsException e) {
916                                GWT.log(e.getMessage(), e);
917                            }
918                        }
919
920                        tree.getStore().remove(categoryModelToDelete);
921                    }
922                });
923            }
924        }
925    };
926
927    private final Listener<MessageBoxEvent> deletePointListener = new Listener<MessageBoxEvent>() {
928        public void handleEvent(MessageBoxEvent ce) {
929            Button btn = ce.getButtonClicked();
930            final PointServiceAsync service = GWT.create(PointService.class);
931
932            if (btn.getText().equals(Const.WORD_YES)) {
933                final Point pointToDelete = pointMap.get(pointModelToDelete.getName());
934                try {
935                    service.deletePoint(pointToDelete, new AsyncCallback<Void>() {
936                        @Override
937                        public void onFailure(Throwable e) {
938                            GWT.log(e.getMessage(), e);
939                        }
940
941                        @Override
942                        public void onSuccess(Void aVoid) {
943                            try {
944                                notifyPointDeletedListener(pointToDelete);
945                                GWT.log("Deleted " + pointToDelete.getName().getValue());
946                            } catch (NimbitsException e) {
947                                GWT.log(e.getMessage(), e);
948                            }
949
950                            tree.getStore().remove(pointModelToDelete);
951                        }
952                    });
953                } catch (NimbitsException e) {
954                    GWT.log(e.getMessage(), e);
955                }
956            }
957        }
958    };
959
960    private final Listener<MessageBoxEvent> deleteDiagramListener = new Listener<MessageBoxEvent>() {
961        public void handleEvent(MessageBoxEvent ce) {
962            Button btn = ce.getButtonClicked();
963            final DiagramServiceAsync service = GWT.create(DiagramService.class);
964
965            if (btn.getText().equals(Const.WORD_YES)) {
966                final Diagram diagramToDelete = diagramMap.get(diagramModelToDelete.getName());
967                service.deleteDiagram(diagramToDelete, new AsyncCallback<Void>() {
968                    @Override
969                    public void onFailure(Throwable e) {
970                        GWT.log(e.getMessage(), e);
971                    }
972
973                    @Override
974                    public void onSuccess(Void aVoid) {
975                        try {
976                            notifyDiagramDeletedListener(diagramToDelete, false);
977                            GWT.log("Deleted " + diagramToDelete.getName());
978                        } catch (NimbitsException e) {
979                            GWT.log(e.getMessage(), e);
980                        }
981
982                        tree.getStore().remove(diagramModelToDelete);
983                    }
984                });
985            }
986        }
987    };
988}