package fi.nls.oskari.control.view;

import fi.nls.oskari.annotation.OskariActionRoute;
import fi.nls.oskari.control.ActionException;
import fi.nls.oskari.control.ActionHandler;
import fi.nls.oskari.control.ActionParameters;
import fi.nls.oskari.domain.map.view.Bundle;
import fi.nls.oskari.domain.map.view.View;
import fi.nls.oskari.domain.map.view.ViewTypes;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.map.view.ViewService;
import fi.nls.oskari.map.view.ViewServiceIbatisImpl;
import fi.nls.oskari.util.ResponseHelper;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.List;

import static fi.nls.oskari.control.ActionConstants.*;

@OskariActionRoute("GetViews")
public class GetViewsHandler extends ActionHandler {

    public static final String KEY_DESCRIPTION = "description";
    public static final String KEY_ISPUBLIC = "isPublic";
    public static final String KEY_ISDEFAULT = "isDefault";
    public static final String KEY_PUBDOMAIN = "pubDomain";
    public static final String KEY_VIEWS = "views";
    public static final String KEY_METADATA = "metadata";

    private static final Logger log = LogFactory.getLogger(GetViewsHandler.class);

    private ViewService viewService = null;


    public void setViewService(final ViewService service) {
        viewService = service;
    }

    public void init() {
        // setup service if it hasn't been initialized
        if (viewService == null) {
            setViewService(new ViewServiceIbatisImpl());
        }
    }

    public void handleAction(final ActionParameters params) throws ActionException {

        final String viewType = params.getHttpParam(ViewTypes.VIEW_TYPE, ViewTypes.USER);

        // require a logged in user when requesting views
        params.requireLoggedInUser();
        final long userId = params.getUser().getId();

        // TODO: send type as second param
        final List<View> views = viewService.getViewsForUser(userId);
        final JSONArray viewArray = new JSONArray();
        for (View view : views) {

            if (view.getType() == null) {
                view.setType(ViewTypes.USER);
            }

            if (!viewType.equalsIgnoreCase(view.getType())) {
                continue;
            }

            final JSONObject viewJson = new JSONObject();
            try {
                viewJson.put(KEY_NAME, view.getName());
                viewJson.put(KEY_DESCRIPTION, view.getDescription());
                viewJson.put(KEY_LANG, view.getLang());
                viewJson.put(KEY_ID, view.getId());
                viewJson.put(KEY_UUID, view.getUuid());
                viewJson.put(KEY_ISPUBLIC, view.isPublic());
                viewJson.put(KEY_ISDEFAULT, view.isDefault());
                viewJson.put(KEY_PUBDOMAIN, view.getPubDomain());
                viewJson.put(KEY_URL, view.getUrl());
                viewJson.put(KEY_METADATA, view.getMetadata());
                // publisher 2 doesn't need the view info since it loads it using id
                // The old publisher and normal view listing need them.
                final JSONObject stateAccu = new JSONObject();
                for (Bundle bundle : view.getBundles()) {

                    final JSONObject bundleNode = new JSONObject();
                    try {
                        bundleNode.put(KEY_STATE, new JSONObject(bundle.getState()));
                        bundleNode.put(KEY_CONFIG, new JSONObject(bundle.getConfig()));
                        stateAccu.put(bundle.getBundleinstance(), bundleNode);
                    } catch (Exception e) {
                        log.debug("Status " + bundle.getStartup());
                        log.debug("Config " + bundle.getConfig());
                    }
                }
                viewJson.put(KEY_STATE, stateAccu);
                viewArray.put(viewJson);

            } catch (Exception ex) {
                log.error("[GetViewsHandler] Failed to parse states "
                        + "for view:", view);
            }

        }

        try {
            JSONObject ret = new JSONObject();
            ret.put(KEY_VIEWS, viewArray);
            ResponseHelper.writeResponse(params, ret);
        } catch (Exception ex) {
            ResponseHelper.writeResponse(params, false);
            log.error(ex);
        }
    }
}

@@ -640,16 +640,52 @@
 il.List;
+%0Aimport java.util.stream.Collectors;
 %0A%0Aimport
@@ -1581,32 +1581,33 @@
        %7D%0A    %7D%0A%0A
+%0A
     public void 
@@ -1679,100 +1679,8 @@
 n %7B%0A
-%0A        final String viewType = params.getHttpParam(ViewTypes.VIEW_TYPE, ViewTypes.USER);%0A%0A
     
@@ -1838,42 +1838,93 @@
     
-// TODO: send type as second param
+final String expectedType = params.getHttpParam(ViewTypes.VIEW_TYPE, ViewTypes.USER);
 %0A   
@@ -2008,46 +2008,54 @@
 nal 
-JSONArray viewArray = new JSONArray
+List%3CView%3E viewsOfCorrectType = views.stream
 ()
-;
 %0A   
@@ -2063,131 +2063,127 @@
     
-for (View view : views) %7B%0A%0A            if (view.getType() == null) %7B%0A                view.setType(ViewTypes.USER
+        .filter(v -%3E isTypeCorrect(expectedType, v.getType()))%0A                .collect(Collectors.toList()
 );%0A
+%0A
         
     
@@ -2182,117 +2182,99 @@
     
-    %7D%0A%0A            if (!viewType.equalsIgnoreCase(view.getType())) %7B%0A                continue;%0A            %7D%0A
+final JSONArray viewArray = new JSONArray();%0A        for (View view : viewsOfCorrectType) %7B
 %0A   
@@ -4354,10 +4354,205 @@
 %7D%0A    %7D%0A
+%0A    private boolean isTypeCorrect(String expected, String type) %7B%0A        if (type == null) %7B%0A            type = ViewTypes.USER;%0A        %7D%0A        return expected.equalsIgnoreCase(type);%0A    %7D%0A%0A
 %7D%0A

Move filtering outside of loop