001/*
002 *  Copyright 2015 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016
017package org.ametys.plugins.survey.clientsideelement;
018
019import java.text.DateFormat;
020import java.util.ArrayList;
021import java.util.Calendar;
022import java.util.Date;
023import java.util.GregorianCalendar;
024import java.util.HashMap;
025import java.util.List;
026import java.util.Locale;
027import java.util.Map;
028
029import org.apache.avalon.framework.context.Context;
030import org.apache.avalon.framework.context.ContextException;
031import org.apache.avalon.framework.context.Contextualizable;
032import org.apache.avalon.framework.service.ServiceException;
033import org.apache.avalon.framework.service.ServiceManager;
034import org.apache.cocoon.components.ContextHelper;
035import org.apache.cocoon.i18n.I18nUtils;
036
037import org.ametys.core.ui.Callable;
038import org.ametys.core.ui.StaticClientSideElement;
039import org.ametys.plugins.repository.AmetysObjectResolver;
040import org.ametys.plugins.survey.repository.Survey;
041import org.ametys.runtime.i18n.I18nizableText;
042import org.ametys.runtime.parameter.ParameterHelper;
043import org.ametys.runtime.parameter.ParameterHelper.ParameterType;
044
045/**
046 * ClientSideElement for the Scheduled Survey
047 */
048public class ScheduledSurveyClientSideElement extends StaticClientSideElement implements Contextualizable
049{
050    private Context _context;
051    private AmetysObjectResolver _resolver;
052
053    @Override
054    public void contextualize(Context context) throws ContextException
055    {
056        _context = context;
057    }
058    
059    @Override
060    public void service(ServiceManager smanager) throws ServiceException
061    {
062        super.service(smanager);
063        _resolver = (AmetysObjectResolver) smanager.lookup(AmetysObjectResolver.ROLE);
064    }
065    
066    /**
067     * Get the scheduled dates of a survey
068     * @param surveyId the id of the survey
069     * @return a map
070     */
071    @Callable
072    public Map<String, Object> getScheduledDates(String surveyId)
073    {
074        Map<String, Object> dates = new HashMap<> ();
075        
076        Survey survey = _resolver.resolveById(surveyId);
077        
078        Date startDate = survey.getStartDate();
079        if (startDate != null)
080        {
081            dates.put("startDate", ParameterHelper.valueToString(startDate));
082        }
083        
084        Date endDate = survey.getEndDate();
085        if (endDate != null)
086        {
087            dates.put("endDate", ParameterHelper.valueToString(endDate));
088        }
089        
090        return dates;
091    }
092    
093    /**
094     * Set date of publication of surveys
095     * @param surveyIds The ids of surveys to update
096     * @param startDateAsStr The start date. Can be null.
097     * @param endDateAsStr The end date. Can be null.
098     * @return true if operation has succeeded.
099     */
100    @Callable
101    public boolean setScheduledDate (List<String> surveyIds, String startDateAsStr, String endDateAsStr)
102    {
103        Date startDate = startDateAsStr != null ? (Date) ParameterHelper.castValue(startDateAsStr, ParameterType.DATE) : null;
104        Date endDate = endDateAsStr != null ? (Date) ParameterHelper.castValue(endDateAsStr, ParameterType.DATE) : null;
105        
106        for (String id : surveyIds)
107        {
108            Survey survey = _resolver.resolveById(id);
109            
110            survey.setStartDate(startDate);
111            survey.setEndDate(endDate);
112            survey.saveChanges();
113        }
114        
115        return true;
116    }
117    
118    /**
119     * Get the survey status
120     * @param surveysId The survey ids
121     * @return the surveys status
122     */
123    @SuppressWarnings("unchecked")
124    @Callable
125    public Map<String, Object> getStatus (List<String> surveysId)
126    {
127        Map<String, Object> results = new HashMap<>();
128        
129        results.put("allright-surveys", new ArrayList<Map<String, Object>>());
130        results.put("scheduled-surveys", new ArrayList<Map<String, Object>>());
131        results.put("scheduled-valid-surveys", new ArrayList<Map<String, Object>>());
132        results.put("scheduled-forthcoming-surveys", new ArrayList<Map<String, Object>>());
133        results.put("scheduled-outofdate-surveys", new ArrayList<Map<String, Object>>());
134        
135        Calendar now = new GregorianCalendar();
136        now.set(Calendar.HOUR_OF_DAY, 0);
137        now.set(Calendar.MINUTE, 0);
138        now.set(Calendar.SECOND, 0);
139        now.set(Calendar.MILLISECOND, 0);
140        
141        for (String surveyId : surveysId)
142        {
143            Survey survey = _resolver.resolveById(surveyId);
144            
145            Map<String, Object> surveyParams = new HashMap<>();
146            surveyParams.put("id", survey.getId());
147            surveyParams.put("title", survey.getTitle());
148            
149            Date startDate = survey.getStartDate();
150            Date endDate = survey.getEndDate();
151            
152            boolean isScheduled = startDate != null || endDate != null;
153            if (isScheduled)
154            {
155                Map objectModel = ContextHelper.getObjectModel(_context);
156                Locale locale = I18nUtils.findLocale(objectModel, "locale", null, Locale.getDefault(), true);
157                
158                if ((startDate == null || !startDate.after(now.getTime())) && (endDate == null || !endDate.before(now.getTime())))
159                {
160                    surveyParams.put("description", _getDateValidDescription(survey));
161                    
162                    List<Map<String, Object>> validSurveys = (List<Map<String, Object>>) results.get("scheduled-valid-surveys");
163                    validSurveys.add(surveyParams);
164                }
165                else if (endDate != null && endDate.before(now.getTime()))
166                {
167                    surveyParams.put("description", _getOutOfDateDescription(survey, endDate, locale));
168                    
169                    List<Map<String, Object>> oodSurveys = (List<Map<String, Object>>) results.get("scheduled-outofdate-surveys");
170                    oodSurveys.add(surveyParams);
171                }
172                else if (startDate != null && startDate.after(now.getTime()))
173                {
174                    surveyParams.put("description", _getForthComingDescription(survey, startDate, endDate, locale));
175                    
176                    List<Map<String, Object>> forthcomingSurveys = (List<Map<String, Object>>) results.get("scheduled-forthcoming-surveys");
177                    forthcomingSurveys.add(surveyParams);
178                }
179                
180                List<Map<String, Object>> scheduledSurveys = (List<Map<String, Object>>) results.get("scheduled-surveys");
181                scheduledSurveys.add(surveyParams);
182            }
183            
184            List<Map<String, Object>> allrightSurveys = (List<Map<String, Object>>) results.get("allright-surveys");
185            allrightSurveys.add(surveyParams);
186        }
187        
188        return results;
189    }
190    
191
192    private I18nizableText _getDateValidDescription (Survey survey)
193    {
194        List<String> i18nParameters = new ArrayList<>();
195        i18nParameters.add(survey.getTitle());
196        
197        I18nizableText ed = (I18nizableText) this._script.getParameters().get("scheduled-survey-valid-description");
198        return new I18nizableText(ed.getCatalogue(), ed.getKey(), i18nParameters);
199    }
200    
201    private I18nizableText _getOutOfDateDescription (Survey survey, Date endDate, Locale locale)
202    {
203        List<String> i18nParameters = new ArrayList<>();
204        i18nParameters.add(survey.getTitle());
205        
206        DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, locale);
207        i18nParameters.add(endDate != null ? df.format(endDate) : "-");
208        
209        I18nizableText ed = (I18nizableText) this._script.getParameters().get("scheduled-survey-outofdate-description");
210        return new I18nizableText(ed.getCatalogue(), ed.getKey(), i18nParameters);
211    }
212    
213    private I18nizableText _getForthComingDescription (Survey survey, Date startDate, Date endDate, Locale locale)
214    {
215        List<String> i18nParameters = new ArrayList<>();
216        i18nParameters.add(survey.getTitle());
217        
218        DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, locale);
219        i18nParameters.add(startDate != null ? df.format(startDate) : "-");
220        i18nParameters.add(endDate != null ? df.format(endDate) : "-");
221        
222        I18nizableText ed = (I18nizableText) this._script.getParameters().get("scheduled-survey-forthcoming-description");
223        return new I18nizableText(ed.getCatalogue(), ed.getKey(), i18nParameters);
224    }
225    
226}