/*
 *  Copyright (C) 2012 Stichting Akvo (Akvo Foundation)
 *
 *  This file is part of Akvo FLOW.
 *
 *  Akvo FLOW is free software: you can redistribute it and modify it under the terms of
 *  the GNU Affero General Public License (AGPL) as published by the Free Software Foundation,
 *  either version 3 of the License or any later version.
 *
 *  Akvo FLOW is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 *  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *  See the GNU Affero General Public License included below for more details.
 *
 *  The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>.
 */

package org.waterforpeople.mapping.app.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import com.gallatinsystems.common.Constants;
import com.gallatinsystems.user.dao.UserAuthorizationDAO;
import com.gallatinsystems.user.dao.UserDao;
import com.gallatinsystems.user.dao.UserRoleDao;
import com.gallatinsystems.user.domain.Permission;
import com.gallatinsystems.user.domain.User;
import com.gallatinsystems.user.domain.UserAuthorization;
import com.gallatinsystems.user.domain.UserRole;
import com.google.appengine.api.users.UserServiceFactory;

public class CurrentUserServlet extends HttpServlet {

    private UserRoleDao userRoleDAO = new UserRoleDao();

    private UserAuthorizationDAO userAuthorizationDAO = new UserAuthorizationDAO();

    private static final long serialVersionUID = -430515593814261770L;
    private static final Logger log = Logger.getLogger(CurrentUserServlet.class
            .getName());

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        final VelocityEngine engine = new VelocityEngine();
        engine.setProperty("runtime.log.logsystem.class",
                "org.apache.velocity.runtime.log.NullLogChute");
        try {
            engine.init();
        } catch (Exception e) {
            log.log(Level.SEVERE, "Could not initialize velocity", e);
        }

        Template t = null;
        try {
            t = engine.getTemplate("CurrentUser.vm");
        } catch (Exception e) {
            log.log(Level.SEVERE, "Could not get the template `CurrentUser`", e);
            return;
        }

        final VelocityContext context = new VelocityContext();
        final UserDao uDao = new UserDao();
        final String currentUserEmail = UserServiceFactory.getUserService()
                .getCurrentUser().getEmail().toLowerCase();
        final User currentUser = uDao.findUserByEmail(currentUserEmail);

        context.put("user", currentUser);
        context.put("permissions", getPermissionsMap(currentUser));

        final StringWriter writer = new StringWriter();
        t.merge(context, writer);

        resp.setContentType("application/javascript;charset=UTF-8");

        final PrintWriter pw = resp.getWriter();
        pw.println(writer.toString());
        pw.close();
    }

    /**
     * Retrieve a javascript map of the paths and corresponding permissions for the current user
     *
     * @param currentUser
     * @return
     */
    private String getPermissionsMap(User currentUser) {
        List<UserAuthorization> authorizationList = userAuthorizationDAO.listByUser(currentUser
                .getKey().getId());
        Map<Long, UserRole> roleMap = new HashMap<Long, UserRole>();
        for (UserRole role : userRoleDAO.list(Constants.ALL_RESULTS)) {
            roleMap.put(role.getKey().getId(), role);
        }
        StringBuilder permissions = new StringBuilder();
        permissions.append("{");
        for (UserAuthorization auth : authorizationList) {
            UserRole role = roleMap.get(auth.getRoleId());
            if (role != null) {
                permissions.append("\"" + auth.getObjectPath() + "\":[");
                for (Permission perm : role.getPermissions()) {
                    permissions.append("\"" + perm.name() + "\",");
                }
                permissions.append("]");
                permissions.append(",");
            }
        }
        if (permissions.lastIndexOf(",") == permissions.length() - 1) {
            permissions.deleteCharAt(permissions.lastIndexOf(","));
        }
        permissions.append("}");

        return permissions.toString();
    }
}

@@ -895,24 +895,46 @@
 a.util.Map;%0A
+import java.util.Set;%0A
 import java.
@@ -1286,16 +1286,169 @@
 yEngine;
+%0Aimport org.codehaus.jackson.JsonGenerationException;%0Aimport org.codehaus.jackson.map.JsonMappingException;%0Aimport org.codehaus.jackson.map.ObjectMapper;
 %0A%0Aimport
@@ -4261,29 +4261,44 @@
         
+Map%3C
 String
-Builder
+, Set%3CPermission%3E%3E
  permiss
@@ -4312,55 +4312,41 @@
 new 
-StringBuilder();%0A        permissions.append(%22%7B%22
+HashMap%3CString, Set%3CPermission%3E%3E(
 );%0A 
@@ -4522,30 +4522,20 @@
 issions.
-append(%22%5C%22%22 + 
+put(
 auth.get
@@ -4550,58 +4550,9 @@
 th()
- + %22%5C%22:%5B%22);%0A                for (Permission perm :
+,
  rol
@@ -4570,18 +4570,17 @@
 sions())
- %7B
+;
 %0A       
@@ -4580,32 +4580,34 @@
             
+%7D%0A
         
 permissions.
@@ -4598,78 +4598,135 @@
     
-permissions.append(%22%5C%22%22 + perm.name() + %22%5C%22,%22);%0A            
+%7D%0A%0A        ObjectMapper jsonObjectMapper = new ObjectMapper();%0A        StringWriter writer = new StringWriter();%0A
     
-%7D%0A
     
+try %7B%0A
     
@@ -4737,73 +4737,103 @@
     
-permissions.append(%22%5D%22);%0A                permissions.append(%22,%22);
+jsonObjectMapper.writeValue(writer, permissions);%0A        %7D catch (JsonGenerationException e) %7B
 %0A   
@@ -4833,33 +4833,41 @@
 ) %7B%0A            
-%7D
+// ignore
 %0A        %7D%0A     
@@ -4864,191 +4864,129 @@
    %7D
-%0A        if (permissions.lastIndexOf(%22,%22) == permissions.length() - 1) %7B%0A            permissions.deleteCharAt(permissions.lastIndexOf(%22,%22));%0A        %7D%0A        permissions.append(%22%7D%22);
+ catch (JsonMappingException e) %7B%0A            // ignore%0A        %7D catch (IOException e) %7B%0A            // ignore%0A        %7D
 %0A%0A  
@@ -4998,27 +4998,22 @@
  return 
-permissions
+writer
 .toStrin

Use jackson Object mapper to generate JSON