package org.oskari.control.userlayer.data;

import org.json.JSONObject;

import fi.nls.oskari.annotation.OskariActionRoute;
import fi.nls.oskari.control.ActionDeniedException;
import fi.nls.oskari.control.ActionException;
import fi.nls.oskari.control.ActionHandler;
import fi.nls.oskari.control.ActionParameters;
import fi.nls.oskari.control.ActionParamsException;
import fi.nls.oskari.domain.map.userlayer.UserLayerStyle;
import fi.nls.oskari.service.OskariComponentManager;
import fi.nls.oskari.util.ConversionHelper;
import fi.nls.oskari.util.ResponseHelper;
import org.oskari.map.userlayer.service.UserLayerDbService;


/**
 * Expects to get layer id as http parameter "id".
 */
@OskariActionRoute("GetUserLayerStyle")
public class GetUserLayerStyleHandler extends ActionHandler {
    private static final String PARAM_ID = "id";
    private UserLayerDbService userLayerDbService;
    
    @Override
    public void init() {
        userLayerDbService = OskariComponentManager.getComponentOfType(UserLayerDbService.class);
    }
    
    public void handleAction(ActionParameters params) throws ActionException {
        params.requireLoggedInUser();

        final long id = params.getRequiredParamLong(PARAM_ID);

        final UserLayerStyle style = userLayerDbService.getUserLayerStyleById(id);
        if (style != null){
            JSONObject response = style.parseUserLayerStyle2JSON();
            ResponseHelper.writeResponse(params, response);
        }else{
            throw new ActionParamsException("Unable to get style for id" + id);
        }        
    }    
}

@@ -416,16 +416,69 @@
 rStyle;%0A
+import fi.nls.oskari.domain.map.userlayer.UserLayer;%0A
 import f
@@ -1264,16 +1264,436 @@
 RAM_ID);
+%0A        //style id == userlayer id%0A        final UserLayer userLayer = userLayerDbService.getUserLayerById(id);%0A        if(userLayer == null) %7B%0A            throw new ActionParamsException(%22Userlayer's style id didn't match any userlayer: %22 + id);%0A        %7D%0A        if(!userLayer.isOwnedBy(params.getUser().getUuid())) %7B%0A            throw new ActionDeniedException(%22Userlayer's style belongs to another user%22);%0A        %7D
 %0A%0A      

check that the style belongs to the current user