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.core.util.DateUtils;
040import org.ametys.plugins.repository.AmetysObjectResolver;
041import org.ametys.plugins.survey.repository.Survey;
042import org.ametys.runtime.i18n.I18nizableText;
043
044/**
045 * ClientSideElement for the Scheduled Survey
046 */
047public class ScheduledSurveyClientSideElement extends StaticClientSideElement implements Contextualizable
048{
049    private Context _context;
050    private AmetysObjectResolver _resolver;
051
052    @Override
053    public void contextualize(Context context) throws ContextException
054    {
055        _context = context;
056    }
057    
058    @Override
059    public void service(ServiceManager smanager) throws ServiceException
060    {
061        super.service(smanager);
062        _resolver = (AmetysObjectResolver) smanager.lookup(AmetysObjectResolver.ROLE);
063    }
064    
065    /**
066     * Get the scheduled dates of a survey
067     * @param surveyId the id of the survey
068     * @return a map
069     */
070    @Callable
071    public Map<String, Object> getScheduledDates(String surveyId)
072    {
073        Map<String, Object> dates = new HashMap<> ();
074        
075        Survey survey = _resolver.resolveById(surveyId);
076        
077        Date startDate = survey.getStartDate();
078        if (startDate != null)
079        {
080            dates.put("startDate", DateUtils.dateToString(startDate));
081        }
082        
083        Date endDate = survey.getEndDate();
084        if (endDate != null)
085        {
086            dates.put("endDate", DateUtils.dateToString(endDate));
087        }
088        
089        return dates;
090    }
091    
092    /**
093     * Set date of publication of surveys
094     * @param surveyIds The ids of surveys to update
095     * @param startDateAsStr The start date. Can be null.
096     * @param endDateAsStr The end date. Can be null.
097     * @return true if operation has succeeded.
098     */
099    @Callable
100    public boolean setScheduledDate (List<String> surveyIds, String startDateAsStr, String endDateAsStr)
101    {
102        Date startDate = startDateAsStr != null ? DateUtils.parse(startDateAsStr) : null;
103        Date endDate = endDateAsStr != null ? DateUtils.parse(endDateAsStr) : null;
104        
105        for (String id : surveyIds)
106        {
107            Survey survey = _resolver.resolveById(id);
108            
109            survey.setStartDate(startDate);
110            survey.setEndDate(endDate);
111            survey.saveChanges();
112        }
113        
114        return true;
115    }
116    
117    /**
118     * Get the survey status
119     * @param surveysId The survey ids
120     * @return the surveys status
121     */
122    @SuppressWarnings("unchecked")
123    @Callable
124    public Map<String, Object> getStatus (List<String> surveysId)
125    {
126        Map<String, Object> results = new HashMap<>();
127        
128        results.put("allright-surveys", new ArrayList<>());
129        results.put("scheduled-surveys", new ArrayList<>());
130        results.put("scheduled-valid-surveys", new ArrayList<>());
131        results.put("scheduled-forthcoming-surveys", new ArrayList<>());
132        results.put("scheduled-outofdate-surveys", new ArrayList<>());
133        
134        Calendar now = new GregorianCalendar();
135        now.set(Calendar.HOUR_OF_DAY, 0);
136        now.set(Calendar.MINUTE, 0);
137        now.set(Calendar.SECOND, 0);
138        now.set(Calendar.MILLISECOND, 0);
139        
140        for (String surveyId : surveysId)
141        {
142            Survey survey = _resolver.resolveById(surveyId);
143            
144            Map<String, Object> surveyParams = new HashMap<>();
145            surveyParams.put("id", survey.getId());
146            surveyParams.put("title", survey.getTitle());
147            
148            Date startDate = survey.getStartDate();
149            Date endDate = survey.getEndDate();
150            
151            boolean isScheduled = startDate != null || endDate != null;
152            if (isScheduled)
153            {
154                Map objectModel = ContextHelper.getObjectModel(_context);
155                Locale locale = I18nUtils.findLocale(objectModel, "locale", null, Locale.getDefault(), true);
156                
157                if ((startDate == null || !startDate.after(now.getTime())) && (endDate == null || !endDate.before(now.getTime())))
158                {
159                    surveyParams.put("description", _getDateValidDescription(survey));
160                    
161                    List<Map<String, Object>> validSurveys = (List<Map<String, Object>>) results.get("scheduled-valid-surveys");
162                    validSurveys.add(surveyParams);
163                }
164                else if (endDate != null && endDate.before(now.getTime()))
165                {
166                    surveyParams.put("description", _getOutOfDateDescription(survey, endDate, locale));
167                    
168                    List<Map<String, Object>> oodSurveys = (List<Map<String, Object>>) results.get("scheduled-outofdate-surveys");
169                    oodSurveys.add(surveyParams);
170                }
171                else if (startDate != null && startDate.after(now.getTime()))
172                {
173                    surveyParams.put("description", _getForthComingDescription(survey, startDate, endDate, locale));
174                    
175                    List<Map<String, Object>> forthcomingSurveys = (List<Map<String, Object>>) results.get("scheduled-forthcoming-surveys");
176                    forthcomingSurveys.add(surveyParams);
177                }
178                
179                List<Map<String, Object>> scheduledSurveys = (List<Map<String, Object>>) results.get("scheduled-surveys");
180                scheduledSurveys.add(surveyParams);
181            }
182            
183            List<Map<String, Object>> allrightSurveys = (List<Map<String, Object>>) results.get("allright-surveys");
184            allrightSurveys.add(surveyParams);
185        }
186        
187        return results;
188    }
189    
190
191    private I18nizableText _getDateValidDescription (Survey survey)
192    {
193        List<String> i18nParameters = new ArrayList<>();
194        i18nParameters.add(survey.getTitle());
195        
196        I18nizableText ed = (I18nizableText) this._script.getParameters().get("scheduled-survey-valid-description");
197        return new I18nizableText(ed.getCatalogue(), ed.getKey(), i18nParameters);
198    }
199    
200    private I18nizableText _getOutOfDateDescription (Survey survey, Date endDate, Locale locale)
201    {
202        List<String> i18nParameters = new ArrayList<>();
203        i18nParameters.add(survey.getTitle());
204        
205        DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, locale);
206        i18nParameters.add(endDate != null ? df.format(endDate) : "-");
207        
208        I18nizableText ed = (I18nizableText) this._script.getParameters().get("scheduled-survey-outofdate-description");
209        return new I18nizableText(ed.getCatalogue(), ed.getKey(), i18nParameters);
210    }
211    
212    private I18nizableText _getForthComingDescription (Survey survey, Date startDate, Date endDate, Locale locale)
213    {
214        List<String> i18nParameters = new ArrayList<>();
215        i18nParameters.add(survey.getTitle());
216        
217        DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, locale);
218        i18nParameters.add(startDate != null ? df.format(startDate) : "-");
219        i18nParameters.add(endDate != null ? df.format(endDate) : "-");
220        
221        I18nizableText ed = (I18nizableText) this._script.getParameters().get("scheduled-survey-forthcoming-description");
222        return new I18nizableText(ed.getCatalogue(), ed.getKey(), i18nParameters);
223    }
224    
225}