summaryrefslogtreecommitdiff
path: root/src/com/p4square/grow/frontend/ChapterCompletePage.java
blob: 2dd1ecffae99e013620592581248b174db07b78c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
/*
 * Copyright 2013 Jesse Morgan
 */

package com.p4square.grow.frontend;

import java.util.Date;
import java.util.Map;

import com.p4square.f1oauth.FellowshipOneIntegrationDriver;
import freemarker.template.Template;

import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.ext.freemarker.TemplateRepresentation;

import org.apache.log4j.Logger;

import com.p4square.fmfacade.FreeMarkerPageResource;

import com.p4square.fmfacade.json.JsonRequestClient;
import com.p4square.fmfacade.json.JsonResponse;
import com.p4square.fmfacade.json.ClientException;

import com.p4square.f1oauth.Attribute;
import com.p4square.f1oauth.F1API;
import com.p4square.f1oauth.F1User;

import com.p4square.grow.config.Config;
import com.p4square.grow.model.TrainingRecord;
import com.p4square.grow.provider.Provider;
import com.p4square.grow.provider.TrainingRecordProvider;

/**
 * This resource displays the transitional page between chapters.
 *
 * @author Jesse Morgan <jesse@jesterpm.net>
 */
public class ChapterCompletePage extends FreeMarkerPageResource {
    private static final Logger LOG = Logger.getLogger(ChapterCompletePage.class);

    private GrowFrontend mGrowFrontend;
    private Config mConfig;
    private JsonRequestClient mJsonClient;
    private Provider<String, TrainingRecord> mTrainingRecordProvider;

    private String mUserId;
    private String mChapter;

    @Override
    public void doInit() {
        super.doInit();

        mGrowFrontend = (GrowFrontend) getApplication();
        mConfig = mGrowFrontend.getConfig();

        mJsonClient = new JsonRequestClient(getContext().getClientDispatcher());
        mTrainingRecordProvider = new TrainingRecordProvider<String>(
                new JsonRequestProvider<TrainingRecord>(
                    getContext().getClientDispatcher(),
                    TrainingRecord.class)) {
            @Override
            public String makeKey(String userid) {
                return getBackendEndpoint() + "/accounts/" + userid + "/training";
            }
        };

        mUserId = getRequest().getClientInfo().getUser().getIdentifier();

        mChapter = getAttribute("chapter");
    }

    /**
     * Return the login page.
     */
    @Override
    protected Representation get() {
        try {
            Map<String, Object> root = getRootObject();

            // Get the training summary
            TrainingRecord trainingRecord = mTrainingRecordProvider.get(mUserId);
            if (trainingRecord == null) {
                // Wait. What? Everyone has a training record...
                setStatus(Status.SERVER_ERROR_INTERNAL);
                return new ErrorPage("Could not retrieve your training record.");
            }

            // Verify they completed the chapter.
            Map<String, Boolean> chapters = trainingRecord.getPlaylist().getChapterStatuses();
            Boolean completed = chapters.get(mChapter);
            if (completed == null || !completed) {
                // Redirect back to training page...
                String nextPage = mConfig.getString("dynamicRoot", "");
                nextPage += "/account/training/" + mChapter;
                getResponse().redirectSeeOther(nextPage);
                return new StringRepresentation("Redirecting to " + nextPage);
            }

            // Publish the training chapter complete attribute.
            assignAttribute();

            // Find the next chapter
            String nextChapter = null;
            {
                int min = Integer.MAX_VALUE;
                for (Map.Entry<String, Boolean> chapter : chapters.entrySet()) {
                    int index = chapterIndex(chapter.getKey());
                    if (!chapter.getValue() && index < min) {
                        min = index;
                        nextChapter = chapter.getKey();
                    }
                }
            }

            String nextOverride = getQueryValue("next");
            if (nextOverride != null) {
                nextChapter = nextOverride;
            }

            root.put("stage", mChapter);
            root.put("nextstage", nextChapter);

            /*
             * We will display one of two transitional pages:
             * 
             * If the next chapter has a forward page, display the forward page.
             * Else, if this chapter is not "Introduction", display the chapter
             * complete message.
             */
            Template t = mGrowFrontend.getTemplate("templates/stage-"
                    + nextChapter + "-forward.ftl");

            if (t == null) {
                // Skip the chapter complete message for "Introduction"
                if ("introduction".equals(mChapter)) {
                    String nextPage = mConfig.getString("dynamicRoot", "");
                    nextPage += "/account/training/" + nextChapter;
                    getResponse().redirectSeeOther(nextPage);
                    return new StringRepresentation("Redirecting to " + nextPage);
                }

                t = mGrowFrontend.getTemplate("templates/stage-complete.ftl");
                if (t == null) {
                    setStatus(Status.CLIENT_ERROR_NOT_FOUND);
                    return ErrorPage.TEMPLATE_NOT_FOUND;
                }
            }

            return new TemplateRepresentation(t, root, MediaType.TEXT_HTML);

        } catch (Exception e) {
            LOG.fatal("Could not render page: " + e.getMessage(), e);
            setStatus(Status.SERVER_ERROR_INTERNAL);
            return ErrorPage.RENDER_ERROR;
        }
    }

    private void assignAttribute() {
        if (!(getRequest().getClientInfo().getUser() instanceof F1User)) {
            // Only useful if the user is from F1.
            return;
        }

        F1User user = (F1User) getRequest().getClientInfo().getUser();

        // Update the attribute.
        String attributeName = "Training Complete - " + mChapter;

        try {
            Attribute attribute = new Attribute(attributeName);
            attribute.setStartDate(new Date());

            F1API f1 = ((FellowshipOneIntegrationDriver) mGrowFrontend.getThirdPartyIntegrationFactory())
                            .getF1Access().getAuthenticatedApi(user);
            if (!f1.addAttribute(user.getIdentifier(), attribute)) {
                LOG.error("addAttribute failed for " + user.getIdentifier() 
                        + " with attribute " + attributeName);
            }
        } catch (Exception e) {
            LOG.error("addAttribute failed for " + user.getIdentifier() 
                    + " with attribute " + attributeName, e);
        }
    }

    /**
     * @return The backend endpoint URI
     */
    private String getBackendEndpoint() {
        return mConfig.getString("backendUri", "riap://component/backend");
    }

    /**
     * Helper method to send a GET to the backend.
     */
    private JsonResponse backendGet(final String uri) {
        LOG.debug("Sending backend GET " + uri);

        final JsonResponse response = mJsonClient.get(getBackendEndpoint() + uri);
        final Status status = response.getStatus();
        if (!status.isSuccess() && !Status.CLIENT_ERROR_NOT_FOUND.equals(status)) {
            LOG.warn("Error making backend request for '" + uri
                    + "'. status = " + response.getStatus().toString());
        }

        return response;
    }

    int chapterIndex(String chapter) {
        if ("leader".equals(chapter)) {
            return 5;
        } else if ("teacher".equals(chapter)) {
            return 4;
        } else if ("disciple".equals(chapter)) {
            return 3;
        } else if ("believer".equals(chapter)) {
            return 2;
        } else if ("seeker".equals(chapter)) {
            return 1;
        } else {
            return Integer.MAX_VALUE;
        }
    }
}