RelatedListTable: Make sure that the tableName is set.
[online-glom:gwt-glom.git] / src / main / java / org / glom / web / client / activity / DetailsActivity.java
1 /*
2  * Copyright (C) 2011 Openismus GmbH
3  *
4  * This file is part of GWT-Glom.
5  *
6  * GWT-Glom is free software: you can redistribute it and/or modify it
7  * under the terms of the GNU Lesser General Public License as published by the
8  * Free Software Foundation, either version 3 of the License, or (at your
9  * option) any later version.
10  *
11  * GWT-Glom is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
14  * for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with GWT-Glom.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 package org.glom.web.client.activity;
21
22 import java.util.List;
23
24 import org.glom.web.client.ClientFactory;
25 import org.glom.web.client.OnlineGlomServiceAsync;
26 import org.glom.web.client.StringUtils;
27 import org.glom.web.client.Utils;
28 import org.glom.web.client.event.LocaleChangeEvent;
29 import org.glom.web.client.event.LocaleChangeEventHandler;
30 import org.glom.web.client.event.QuickFindChangeEvent;
31 import org.glom.web.client.event.QuickFindChangeEventHandler;
32 import org.glom.web.client.event.TableChangeEvent;
33 import org.glom.web.client.event.TableChangeEventHandler;
34 import org.glom.web.client.place.DetailsPlace;
35 import org.glom.web.client.place.DocumentSelectionPlace;
36 import org.glom.web.client.place.ListPlace;
37 import org.glom.web.client.ui.DetailsView;
38 import org.glom.web.client.ui.cell.NavigationButtonCell;
39 import org.glom.web.client.ui.details.DetailsCell;
40 import org.glom.web.client.ui.details.Portal;
41 import org.glom.web.client.ui.details.RelatedListTable;
42 import org.glom.web.shared.DataItem;
43 import org.glom.web.shared.DetailsLayoutAndData;
44 import org.glom.web.shared.NavigationRecord;
45 import org.glom.web.shared.TypedDataItem;
46 import org.glom.web.shared.libglom.layout.LayoutGroup;
47 import org.glom.web.shared.libglom.layout.LayoutItemField;
48 import org.glom.web.shared.libglom.layout.LayoutItemPortal;
49
50 import com.google.gwt.cell.client.ValueUpdater;
51 import com.google.gwt.core.client.GWT;
52 import com.google.gwt.dom.client.Element;
53 import com.google.gwt.dom.client.NativeEvent;
54 import com.google.gwt.event.dom.client.ClickEvent;
55 import com.google.gwt.event.dom.client.ClickHandler;
56 import com.google.gwt.event.shared.EventBus;
57 import com.google.gwt.user.client.rpc.AsyncCallback;
58 import com.google.gwt.user.client.ui.AcceptsOneWidget;
59
60 /**
61  *
62  */
63 public class DetailsActivity extends HasTableActivity {
64         /*
65          * Cell renderer for the related list open buttons. Normally this wouldn't be in an Activity class but since it's
66          * making a call to the server it makes sense for it to be here.
67          */
68         private class RelatedListNavigationButtonCell extends NavigationButtonCell {
69
70                 private final String relationshipName;
71
72                 public RelatedListNavigationButtonCell(final String relationshipName) {
73                         this.relationshipName = relationshipName;
74                 }
75
76                 /*
77                  * (non-Javadoc)
78                  * 
79                  * @see com.google.gwt.cell.client.ButtonCell#onEnterKeyDown(com.google.gwt.cell.client.Cell.Context,
80                  * com.google.gwt.dom.client.Element, java.lang.String, com.google.gwt.dom.client.NativeEvent,
81                  * com.google.gwt.cell.client.ValueUpdater)
82                  */
83                 @Override
84                 protected void onEnterKeyDown(final Context context, final Element parent, final String value,
85                                 final NativeEvent event, final ValueUpdater<String> valueUpdater) {
86                         final AsyncCallback<NavigationRecord> callback = new AsyncCallback<NavigationRecord>() {
87                                 @Override
88                                 public void onFailure(final Throwable caught) {
89                                         // TODO: create a way to notify users of asynchronous callback failures
90                                         GWT.log("AsyncCallback Failed: OnlineGlomService.getSuitableRecordToViewDetails(): "
91                                                         + caught.getMessage());
92                                 }
93
94                                 @Override
95                                 public void onSuccess(final NavigationRecord result) {
96                                         if(result != null) {
97                                                 processNavigation(result.getTableName(), result.getPrimaryKeyValue());
98                                         } else {
99                                                 GWT.log("onEnterKeyDown(): getSuitableRecordToViewDetails() result is null.");
100                                         }
101                                 }
102
103                         };
104                         
105                         //TODO: tableName is not set here.
106                         OnlineGlomServiceAsync.Util.getInstance().getSuitableRecordToViewDetails(documentID, tableName,
107                                         relationshipName, (TypedDataItem) context.getKey(), callback);
108                 }
109         }
110
111         private TypedDataItem primaryKeyValue;
112         private final DetailsView detailsView;
113         List<DetailsCell> detailsCells;
114         List<Portal> portals;
115
116         public DetailsActivity(final DetailsPlace place, final ClientFactory clientFactory) {
117                 super(place, clientFactory);
118                 this.primaryKeyValue = place.getPrimaryKeyValue();
119                 detailsView = clientFactory.getDetailsView();
120         }
121
122         /*
123          * (non-Javadoc)
124          * 
125          * @see com.google.gwt.activity.shared.Activity#start(com.google.gwt.user.client.ui.AcceptsOneWidget,
126          * com.google.gwt.event.shared.EventBus)
127          */
128         @Override
129         public void start(final AcceptsOneWidget panel, final EventBus eventBus) {
130                 if (StringUtils.isEmpty(documentID))
131                         goTo(new DocumentSelectionPlace());
132
133                 // register this class as the presenter
134                 detailsView.setPresenter(this);
135
136                 // TODO here's where we should check for database authentication - see ListActivity.start() for how to do this
137
138                 // set the change handler for the table selection widget
139                 // TODO: Why don't we just use goTo() in the TableSelectionActivity that fired this event?
140                 eventBus.addHandler(TableChangeEvent.TYPE, new TableChangeEventHandler() {
141                         @Override
142                         public void onTableChange(final TableChangeEvent event) {
143                                 // note the empty primary key item
144                                 goTo(new DetailsPlace(documentID, event.getNewTableName(), new TypedDataItem()));
145                         }
146                 });
147
148                 // get the layout and data for the DetailsView
149                 final AsyncCallback<DetailsLayoutAndData> callback = new AsyncCallback<DetailsLayoutAndData>() {
150                         @Override
151                         public void onFailure(final Throwable caught) {
152                                 // TODO: create a way to notify users of asynchronous callback failures
153                                 GWT.log("AsyncCallback Failed: OnlineGlomService.getDetailsLayoutAndData(): " + caught.getMessage());
154                         }
155
156                         @Override
157                         public void onSuccess(final DetailsLayoutAndData result) {
158                                 if (result == null) {
159                                         // The result is null only when the documentID was not found. There's nothing to display without the
160                                         // documentID.
161                                         goTo(new DocumentSelectionPlace());
162                                 } else {
163                                         // create the layout and set the data
164                                         createLayout(result.getLayout());
165                                         setData(result.getData());
166                                 }
167                         }
168
169                 };
170
171                 final String localeID = Utils.getCurrentLocaleID();
172                 OnlineGlomServiceAsync.Util.getInstance().getDetailsLayoutAndData(documentID, tableName, primaryKeyValue,
173                                 localeID, callback);
174
175                 // set the change handler for the quickfind text widget
176                 eventBus.addHandler(QuickFindChangeEvent.TYPE, new QuickFindChangeEventHandler() {
177                         @Override
178                         public void onQuickFindChange(final QuickFindChangeEvent event) {
179                                 // We switch to the List view, to show search results.
180                                 // TODO: Show the details view if there is only one result.
181                                 goTo(new ListPlace(documentID, tableName, event.getNewQuickFindText()));
182                         }
183                 });
184
185                 // Set the change handler for the table selection widget
186                 eventBus.addHandler(LocaleChangeEvent.TYPE, new LocaleChangeEventHandler() {
187                         @Override
188                         public void onLocaleChange(final LocaleChangeEvent event) {
189                                 // note the empty primary key item
190                                 goTo(new DetailsPlace(documentID, tableName, primaryKeyValue));
191                         }
192                 });
193
194                 // indicate that the view is ready to be displayed
195                 panel.setWidget(detailsView.asWidget());
196         }
197
198         /*
199          * Create the layout.
200          */
201         private void createLayout(final List<LayoutGroup> list) {
202                 // add the groups
203                 for (final LayoutGroup layoutGroup : list) {
204                         detailsView.addGroup(layoutGroup);
205                 }
206
207                 // save references to the DetailsCells and the Portals
208                 detailsCells = detailsView.getCells();
209                 portals = detailsView.getPortals();
210
211                 // Setup click handlers for the navigation buttons
212                 for (final DetailsCell detailsCell : detailsCells) {
213                         final LayoutItemField layoutItemField = detailsCell.getLayoutItemField();
214                         if (layoutItemField == null) {
215                                 continue;
216                         }
217                         if (layoutItemField.getAddNavigation()) {
218                                 detailsCell.setOpenButtonClickHandler(new ClickHandler() {
219                                         @Override
220                                         public void onClick(final ClickEvent event) {
221                                                 final TypedDataItem primaryKeyItem = Utils.getTypedDataItem(layoutItemField.getGlomType(),
222                                                                 detailsCell.getData());
223                                                 processNavigation(layoutItemField.getNavigationTableName(), primaryKeyItem);
224
225                                         }
226                                 });
227                         }
228                 }
229
230         }
231
232         /*
233          * Set the data.
234          */
235         private void setData(final DataItem[] data) {
236
237                 if (data == null)
238                         return;
239
240                 // TODO create proper client side logging
241                 if (data.length != detailsCells.size())
242                         GWT.log("Warning: The number of data items doesn't match the number of data detailsCells.");
243
244                 for (int i = 0; i < Math.min(detailsCells.size(), data.length); i++) {
245                         final DetailsCell detailsCell = detailsCells.get(i);
246                         if (data[i] != null) {
247
248                                 // set the DatailsItem
249                                 detailsCell.setData(data[i]);
250                                 final LayoutItemField layoutItemField = detailsCell.getLayoutItemField();
251                                 final String fieldName = layoutItemField.getName();
252
253                                 // see if there are any related lists that need to be setup
254                                 for (final Portal portal : portals) {
255                                         final LayoutItemPortal layoutItemPortal = portal.getLayoutItem();
256                                         final String portalFromField = layoutItemPortal.getFromField();
257                                         if (fieldName.equals(portalFromField)) {
258                                                 if (data[i] == null)
259                                                         continue;
260
261                                                 final TypedDataItem foreignKeyValue = Utils.getTypedDataItem(layoutItemField.getGlomType(),
262                                                                 data[i]);
263
264                                                 final RelatedListTable relatedListTable = new RelatedListTable(documentID, tableName, layoutItemPortal,
265                                                                 foreignKeyValue, new RelatedListNavigationButtonCell(layoutItemPortal.getRelationshipNameUsed()));
266
267                                                 if (layoutItemPortal.getNavigationType() == LayoutItemPortal.NavigationType.NAVIGATION_NONE) {
268                                                         relatedListTable.hideNavigationButtons();
269                                                 }
270                                                 portal.setContents(relatedListTable);
271
272                                                 setRowCountForRelatedListTable(relatedListTable, layoutItemPortal.getRelationshipNameUsed(), foreignKeyValue);
273                                         }
274                                 }
275                         }
276                 }
277         }
278
279         private void refreshData() {
280
281                 // get the data for the DetailsView
282                 final AsyncCallback<DataItem[]> callback = new AsyncCallback<DataItem[]>() {
283                         @Override
284                         public void onFailure(final Throwable caught) {
285                                 // TODO: create a way to notify users of asynchronous callback failures
286                                 GWT.log("AsyncCallback Failed: OnlineGlomService.getDetailsData(): " + caught.getMessage());
287                         }
288
289                         @Override
290                         public void onSuccess(final DataItem[] result) {
291                                 setData(result);
292                         }
293                 };
294
295                 OnlineGlomServiceAsync.Util.getInstance().getDetailsData(documentID, tableName, primaryKeyValue, callback);
296
297         }
298
299         // sets the row count for the related list table
300         private void setRowCountForRelatedListTable(final RelatedListTable relatedListTable, final String relationshipName,
301                         final TypedDataItem foreignKeyValue) {
302                 final AsyncCallback<Integer> callback = new AsyncCallback<Integer>() {
303                         @Override
304                         public void onFailure(final Throwable caught) {
305                                 // TODO: create a way to notify users of asynchronous callback failures
306                                 GWT.log("AsyncCallback Failed: OnlineGlomService.getRelatedListRowCount(): " + caught.getMessage());
307                         }
308
309                         @Override
310                         public void onSuccess(final Integer result) {
311                                 if (result.intValue() <= relatedListTable.getMinNumVisibleRows()) {
312                                         // Set the table row count to the minimum row count if the data row count is less than or equal to
313                                         // the minimum row count. This ensures that data with fewer rows than the minimum will not create
314                                         // indexes in the underlying CellTable that will override the rendering of the empty rows.
315                                         relatedListTable.setRowCount(relatedListTable.getMinNumVisibleRows());
316                                 } else {
317                                         // Set the table row count to the data row count if it's larger than the minimum number of rows
318                                         // visible.
319                                         relatedListTable.setRowCount(result.intValue());
320                                 }
321                         }
322                 };
323
324                 OnlineGlomServiceAsync.Util.getInstance().getRelatedListRowCount(documentID, tableName, relationshipName,
325                                 foreignKeyValue, callback);
326         }
327
328         /*
329          * Process a navigation by either doing: nothing if the navigation isn't valid, refreshing the data for the current
330          * table with a new primary key, or going to a new table with a new primary key.
331          */
332         private void processNavigation(final String navigationTableName, final TypedDataItem navigationPrimaryKeyValue) {
333
334                 // Ensure the new table name is valid.
335                 String newTableName;
336                 if (!StringUtils.isEmpty(navigationTableName)) {
337                         newTableName = navigationTableName;
338                 } else {
339                         newTableName = tableName;
340                 }
341
342                 // Only process the navigation if there's a valid primary key value.
343                 if (navigationPrimaryKeyValue != null && !navigationPrimaryKeyValue.isEmpty()) {
344                         if (!newTableName.equals(tableName)) {
345                                 // Go to a new DetailsPlace because the table name has changed.
346                                 goTo(new DetailsPlace(documentID, newTableName, navigationPrimaryKeyValue));
347                         } else {
348                                 // Refresh the details view with the new primary because the table name has not changed.
349                                 primaryKeyValue = navigationPrimaryKeyValue;
350                                 refreshData();
351                         }
352                 } else {
353                         // TODO notify the user that navigation isn't possible.
354                         // This is what Glom displays:
355                         // Frame_Glom::show_ok_dialog(_("No Corresponding Record Exists"),
356                         // _("No record with this value exists. Therefore navigation to the related record is not possible."),
357                         // *window, Gtk::MESSAGE_WARNING);
358                         // TODO: Make it more clear to the user exactly what record, what field, and what value, we are talking
359                         // about.
360                 }
361         }
362
363         /*
364          * (non-Javadoc)
365          * 
366          * @see com.google.gwt.activity.shared.Activity#onCancel()
367          */
368         @Override
369         public void onCancel() {
370                 detailsView.clear();
371         }
372
373         /*
374          * (non-Javadoc)
375          * 
376          * @see com.google.gwt.activity.shared.Activity#onStop()
377          */
378         @Override
379         public void onStop() {
380                 detailsView.clear();
381         }
382
383 }