001    /**
002     * Copyright 2010 The Kuali Foundation Licensed under the
003     * Educational Community License, Version 2.0 (the "License"); you may
004     * not use this file except in compliance with the License. You may
005     * obtain a copy of the License at
006     *
007     * http://www.osedu.org/licenses/ECL-2.0
008     *
009     * Unless required by applicable law or agreed to in writing,
010     * software distributed under the License is distributed on an "AS IS"
011     * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
012     * or implied. See the License for the specific language governing
013     * permissions and limitations under the License.
014     */
015    package org.kuali.student.lum.common.client.widgets;
016    
017    import java.util.ArrayList;
018    import java.util.List;
019    
020    import org.kuali.student.common.ui.client.configurable.mvc.layouts.BasicLayout;
021    import org.kuali.student.common.ui.client.configurable.mvc.sections.Section;
022    import org.kuali.student.common.ui.client.mvc.*;
023    import org.kuali.student.common.ui.client.service.DataSaveResult;
024    import org.kuali.student.common.ui.client.widgets.progress.BlockingTask;
025    import org.kuali.student.common.ui.client.widgets.progress.KSBlockingProgressIndicator;
026    import org.kuali.student.common.ui.client.widgets.rules.AccessWidgetValue;
027    import org.kuali.student.core.assembly.data.Data;
028    import org.kuali.student.core.assembly.data.Metadata;
029    import org.kuali.student.core.validation.dto.ValidationResultInfo;
030    import org.kuali.student.core.validation.dto.ValidationResultInfo.ErrorLevel;
031    
032    import com.google.gwt.core.client.GWT;
033    import com.google.gwt.user.client.Window;
034    import com.google.gwt.user.client.ui.FlowPanel;
035    
036    public class BuildCluSetWidget extends FlowPanel implements AccessWidgetValue {
037    
038        private CluSetRetriever cluSetRetriever;
039        private CluSetEditorWidget cluSetEditorWidgetView;
040        private static final String CLUSET_MODEL_ID = "clussetModelId";
041        private DataModel ruleFieldsData;
042        private BasicLayout reqCompController;
043        public enum BuildCourseView {VIEW}
044        private BlockingTask retrievingTask = new BlockingTask("Retrieving ...");
045        private String cluSetType;
046        private String metadataId;
047        private String itemLabel;
048        private boolean singularCluOnly;
049    
050        public BuildCluSetWidget(final CluSetRetriever cluSetRetriever, String cluSetType,
051                boolean singularCluOnly) {
052            super();
053    
054            this.singularCluOnly = singularCluOnly;
055            cluSetEditorWidgetView = new CluSetEditorWidget(
056                    new CluSetRetrieverImpl(),
057                    BuildCourseView.VIEW,
058                    "", CLUSET_MODEL_ID, false,
059                    null, cluSetType, singularCluOnly);
060    
061            ruleFieldsData = new DataModel();
062            ruleFieldsData.setRoot(new Data());
063            this.cluSetType = cluSetType;
064            if (cluSetType != null && cluSetType.equals("kuali.cluSet.type.Program")) {
065                this.metadataId = "programSet";
066                this.itemLabel = "program";
067            } else {
068                this.metadataId = "courseSet";
069                this.itemLabel = "course";
070            }
071    
072            //setup controller
073            final CluSetRetriever theRetriever = cluSetRetriever;
074            this.cluSetRetriever = cluSetRetriever;
075            reqCompController = new BasicLayout(null);
076            reqCompController.addView(cluSetEditorWidgetView);
077            reqCompController.setDefaultModelId(CLUSET_MODEL_ID);
078            reqCompController.registerModel(CLUSET_MODEL_ID, new ModelProvider<DataModel>() {
079                @Override
080                public void requestModel(final ModelRequestCallback<DataModel> callback) {
081                    if (ruleFieldsData.getDefinition() == null) {
082                        theRetriever.getMetadata(metadataId, new Callback<Metadata>(){
083                            @Override
084                            public void exec(Metadata result) {
085                                DataModelDefinition def = new DataModelDefinition(result);
086                                ruleFieldsData.setDefinition(def);
087                                callback.onModelReady(ruleFieldsData);
088                            }
089                        });
090                    } else {
091                        callback.onModelReady(ruleFieldsData);
092                    }
093                }
094            });
095    
096            reqCompController.showView(BuildCourseView.VIEW);
097            add(reqCompController);
098        }
099    
100        @Override
101        public void setValue(final String cluSetId) {
102            if (cluSetId != null) {
103                KSBlockingProgressIndicator.addTask(retrievingTask);
104                cluSetRetriever.getData(cluSetId,  new Callback<Data>() {
105                    @Override
106                    public void exec(Data result) {
107                        try {
108                            ruleFieldsData.setRoot(result);
109                            cluSetEditorWidgetView.updateView(ruleFieldsData);
110                            reqCompController.showView(BuildCourseView.VIEW);
111                        } finally {
112                            KSBlockingProgressIndicator.removeTask(retrievingTask);
113                        }
114                    }
115                });
116            }
117        }
118    
119        @Override
120        public void initWidget(List<Metadata> fieldsMetadata) {
121        }
122    
123        @Override
124        public void getValue(final Callback<String> doneSaveCallback) {
125            GWT.log("CluSetManagementController received save action request.", null);
126            reqCompController.getCurrentView().updateModel();
127            if(ruleFieldsData!=null){
128                ruleFieldsData.validate(new Callback<List<ValidationResultInfo>>() {
129                    @Override
130                    public void exec(List<ValidationResultInfo> result) {
131        
132                        boolean save = true;
133                        View v = reqCompController.getCurrentView();
134                        if(v instanceof Section){
135                            ((Section) v).setFieldHasHadFocusFlags(true);
136                            ErrorLevel status = ((Section) v).processValidationResults(result);
137                            if(status == ErrorLevel.ERROR){
138                                save = false;
139                            }
140                        }
141        
142                        if(save){
143                            reqCompController.getCurrentView().updateModel();
144                            reqCompController.updateModel();
145                            // set reusable flag here for CluSetManagement.
146                            Calendar startCal = new GregorianCalendar();
147                            startCal.set(Calendar.YEAR, 1990);
148                            startCal.set(Calendar.MONTH, Calendar.JANUARY);
149                            startCal.set(Calendar.DATE, 1);
150                            startCal.set(Calendar.HOUR_OF_DAY, 1);
151                            startCal.set(Calendar.MINUTE, 0);
152                            startCal.set(Calendar.SECOND, 0);
153                            Calendar endCal = new GregorianCalendar();
154                            endCal.set(Calendar.YEAR, 2200);
155                            endCal.set(Calendar.MONTH, Calendar.JANUARY);
156                            endCal.set(Calendar.DATE, 1);
157                            endCal.set(Calendar.HOUR_OF_DAY, 1);
158                            endCal.set(Calendar.MINUTE, 0);
159                            endCal.set(Calendar.SECOND, 0);
160                            CluSetHelper cluSetHelper = CluSetHelper.wrap(ruleFieldsData.getRoot());
161                            cluSetHelper.setType(cluSetType);
162                            cluSetHelper.setName("AdHock");
163                            cluSetHelper.setReusable(new Boolean(false));
164                            cluSetHelper.setReferenceable(new Boolean(false));
165                            cluSetHelper.setEffectiveDate(startCal.getTime());
166                            cluSetHelper.setEffectiveDate(endCal.getTime());
167                            
168                            int numClus = 0;
169                            if (cluSetHelper.getApprovedClus() != null) {
170                                List<String> approvedCluIds = new ArrayList<String>();
171                                for (Data.Property p : cluSetHelper.getApprovedClus()) {
172                                    if(!"_runtimeData".equals(p.getKey())){
173                                        String approvedCluId = p.getValue();
174                                        approvedCluIds.add(approvedCluId);
175                                    }
176                                }
177                                numClus = numClus + approvedCluIds.size();
178                            }
179                            if (cluSetHelper.getProposedClus() != null) {
180                                List<String> proposedCluIds = new ArrayList<String>();
181                                for (Data.Property p : cluSetHelper.getProposedClus()) {
182                                    if(!"_runtimeData".equals(p.getKey())){
183                                        String proposedCluId = p.getValue();
184                                        proposedCluIds.add(proposedCluId);
185                                    }
186                                }
187                                numClus = numClus + proposedCluIds.size();
188                            }
189                            if (singularCluOnly && numClus > 1) {
190                                Window.alert("Only one " + itemLabel + " is allowed.  " +
191                                        "Please delete all " + itemLabel + " until there is only one left.");
192                            } else {
193                                cluSetRetriever.saveData(ruleFieldsData.getRoot(), new Callback<DataSaveResult>() {
194                                    @Override
195                                    public void exec(DataSaveResult result) {
196                                        if (result.getValidationResults() != null &&
197                                                !result.getValidationResults().isEmpty()) {
198                                            StringBuilder errorMessage = new StringBuilder();
199                                            errorMessage.append("Validation error: ");
200                                            for (ValidationResultInfo validationError : result.getValidationResults()) {
201                                                errorMessage.append(validationError.getMessage()).append(" ");
202                                            }
203                                            doneSaveCallback.exec(null);
204                                            Window.alert(errorMessage.toString());
205                                        } else {
206                                            ruleFieldsData.setRoot(result.getValue());
207                                            CluSetHelper helper = CluSetHelper.wrap((Data)ruleFieldsData.getRoot());
208                                            String cluSetId = helper.getId();
209                                            Data approvedClusData = helper.getApprovedClus();
210                                            Data proposedClusData = helper.getProposedClus();
211                                            String cluId = null;
212                                            if (singularCluOnly) {
213                                                if (cluId == null && approvedClusData != null) {
214                                                    for (Data.Property p : approvedClusData) {
215                                                        if(!"_runtimeData".equals(p.getKey())){
216                                                            cluId = p.getValue();
217                                                            break;
218                                                        }
219                                                    }
220                                                }
221                                                if (cluId == null && proposedClusData != null) {
222                                                    for (Data.Property p : proposedClusData) {
223                                                        if(!"_runtimeData".equals(p.getKey())){
224                                                            cluId = p.getValue();
225                                                            break;
226                                                        }
227                                                    }
228                                                }
229                                                doneSaveCallback.exec(cluId);
230                                            } else {
231                                                doneSaveCallback.exec(cluSetId);
232                                            }
233                                        }
234                                    }
235                                });
236                            }
237                        }
238                        else {
239                            Window.alert("Save failed.  Please check fields for errors.");
240                        }
241    
242                    }
243                });
244            }
245        }
246        
247    }