/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

package org.pentaho.cdf.views;

import java.io.OutputStream;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.pentaho.platform.api.engine.IParameterProvider;
import org.pentaho.platform.api.engine.IPentahoSession;
import org.pentaho.platform.engine.core.system.PentahoSessionHolder;
import pt.webdetails.cpf.persistence.*;

/**
 *
 * @author pdpi
 */
public class ViewManager {

    private static ViewManager instance;
    private static final Log logger = LogFactory.getLog(ViewManager.class);

    private ViewManager() {
    }

    public synchronized static ViewManager getInstance() {
        if (instance == null) {
            instance = new ViewManager();
        }
        return instance;
    }

    public void process(IParameterProvider requestParams, IParameterProvider pathParams, OutputStream out) {

        String method = requestParams.getStringParameter("method", "");
        if ("listViews".equals(method)) {
            try {
                out.write(listViews().toString(2).getBytes("utf-8"));
            } catch (Exception e) {
                logger.error("Error listing views: " + e);
            }
        } else if ("saveView".equals(method)) {
            try {
                out.write(saveView(requestParams, pathParams).getBytes("utf-8"));
            } catch (Exception e) {
                logger.error("Error saving view: " + e);
            }
        } else if ("deleteView".equals(method)) {
            try {
                out.write(deleteView(requestParams, pathParams).getBytes("utf-8"));
            } catch (Exception e) {
                logger.error("Error saving view: " + e);
            }
        }else {
            logger.error("Unsupported method");
        }
    }

    public View getView(String id) {
        IPentahoSession userSession = PentahoSessionHolder.getSession();
        SimplePersistence sp = SimplePersistence.getInstance();
        Filter filter = new Filter();
        filter.where("name").equalTo(id).and().where("user").equalTo(userSession.getName());
        List<View> views = sp.load(View.class, filter);

        return (views != null && views.size() > 0) ? views.get(0) : null;
    }

    public JSONObject listViews() {
        IPentahoSession userSession = PentahoSessionHolder.getSession();
        SimplePersistence sp = SimplePersistence.getInstance();
        Filter filter = new Filter();
        filter.where("user").equalTo(userSession.getName());
        List<View> views = sp.load(View.class, filter);
        JSONObject obj = new JSONObject();
        JSONArray arr = new JSONArray();
        for (View v : views) {
            arr.put(v.toJSON());
        }
        try {
            obj.put("views", arr);
            obj.put("status", "ok");
        } catch (JSONException e) {
        }
        return obj;
    }

    public String saveView(IParameterProvider requestParams, IParameterProvider pathParams) {
        View view = new View();
        IPentahoSession userSession = PentahoSessionHolder.getSession();

        try {
            JSONObject json = new JSONObject(requestParams.getStringParameter("view", ""));
            view.fromJSON(json);
            view.setUser(userSession.getName());
            PersistenceEngine pe = PersistenceEngine.getInstance();
            pe.store(view);
        } catch (JSONException e) {
            logger.error(e);
            return "error";
        }
        return "ok";
    }

    public String deleteView(IParameterProvider requestParams, IParameterProvider pathParams) {
        IPentahoSession userSession = PentahoSessionHolder.getSession();
        try {
            String name = requestParams.getStringParameter("name", "");
            Filter filter = new Filter();
            filter.where("user").equalTo(userSession.getName()).and().where("name").equalTo(name);
            SimplePersistence.getInstance().delete(View.class, filter);
            return "ok";
        } catch (Exception e) {
            return "error";
        }
    }

    public void listReports() {
    }

    public void saveReport() {
    }
}

@@ -198,17 +198,16 @@
 .0/. */%0A
-%0A
 package 
@@ -633,24 +633,84 @@
 sionHolder;%0A
+import org.pentaho.platform.engine.security.SecurityHelper;%0A
 import pt.we
@@ -1534,32 +1534,284 @@
 ;%0A            %7D%0A
+        %7D else if (%22listAllViews%22.equals(method)) %7B%0A            try %7B%0A                out.write(listAllViews().toString(2).getBytes(%22utf-8%22));%0A            %7D catch (Exception e) %7B%0A                logger.error(%22Error listing views: %22 + e);%0A            %7D%0A
         %7D else i
@@ -2317,16 +2317,17 @@
        %7D
+ 
 else %7B%0A 
@@ -3443,32 +3443,32 @@
  e) %7B%0A        %7D%0A
-
         return o
@@ -3470,32 +3470,1016 @@
 urn obj;%0A    %7D%0A%0A
+    public JSONObject listAllViews() %7B%0A        JSONObject response = new JSONObject();%0A        IPentahoSession userSession = PentahoSessionHolder.getSession();%0A        if (!SecurityHelper.isPentahoAdministrator(userSession)) %7B%0A            try %7B%0A                response.put(%22status%22, %22error%22);%0A                response.put(%22message%22, %22You need to be an administrator to poll all views%22);%0A            %7D catch (JSONException e) %7B%0A            %7D%0A            return response;%0A        %7D%0A        SimplePersistence sp = SimplePersistence.getInstance();%0A        Filter filter = new Filter();%0A        filter.where(%22user%22).equalTo(userSession.getName());%0A        List%3CView%3E views = sp.loadAll(View.class);%0A        JSONArray arr = new JSONArray();%0A        for (View v : views) %7B%0A            arr.put(v.toJSON());%0A        %7D%0A        try %7B%0A            response.put(%22views%22, arr);%0A            response.put(%22status%22, %22ok%22);%0A        %7D catch (JSONException e) %7B%0A        %7D%0A        return response;%0A    %7D%0A%0A
     public Strin

Add a listAllViews method for administrators to list all registered views.