package flyway.oskari;

import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.util.JSONHelper;
import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;
import org.json.JSONObject;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class V2_3_1__migrate_wps_params extends BaseJavaMigration {
    private static final Logger LOG = LogFactory.getLogger(V2_3_1__migrate_wps_params.class);
    public static final String WPS_PARAMS = "wpsParams";

    @Override
    public void migrate(Context context) throws Exception {
        Connection conn = context.getConnection();
        getLayerAttributes(conn).forEach((id, attr) -> migrateWpsParams(conn, id, attr));
    }
    private void migrateWpsParams (Connection conn, int id, JSONObject attr) {
        String wpsString = attr.optString(WPS_PARAMS);
        if (wpsString.isEmpty()) {
            //skip
            return;
        }
        try {
            JSONObject wpsParams = new JSONObject(wpsString);
            JSONHelper.putValue(attr, WPS_PARAMS, wpsParams);
            updateAttributes(conn, id, attr);
        } catch (Exception ignored) {
            LOG.warn("Failed to migrate WPS params String:", wpsString, "to JSONObject for layer:", id);
        }
    }
    private void updateAttributes (Connection conn, int layerId, JSONObject attributes) throws SQLException {
        final String sql = "UPDATE oskari_maplayer SET attributes=? where id=?";
        try(PreparedStatement statement = conn.prepareStatement(sql)) {
            statement.setString(1, attributes.toString());
            statement.setInt(2, layerId);
            statement.execute();
        }
    }
    private Map<Integer, JSONObject> getLayerAttributes(Connection conn) throws SQLException {
        Map<Integer, JSONObject> attributes = new HashMap<>();
        // only WFS layers have WPS params
        final String sql = "SELECT id, attributes FROM oskari_maplayer where type = 'wfslayer'";
        try(PreparedStatement statement = conn.prepareStatement(sql)) {
            try (ResultSet rs = statement.executeQuery()) {
                while(rs.next()) {
                    int id = rs.getInt("id");
                    JSONObject attr = JSONHelper.createJSONObject(rs.getString("attributes"));
                    attributes.put(id, attr);
                }
            }
        }
        LOG.info("Found", attributes.size(), "WFS layers for WPS migration");
        return attributes;
    }
}

@@ -406,16 +406,43 @@
 ashMap;%0A
+import java.util.Iterator;%0A
 import j
@@ -455,16 +455,16 @@
 il.Map;%0A
-
 %0Apublic 
@@ -1211,53 +1211,830 @@
 JSON
-Helper.putValue(attr, WPS_PARAMS, wpsParams);
+Object data = attr.optJSONObject(%22data%22);%0A            if (data == null) %7B%0A                data = new JSONObject();%0A            %7D%0A            Iterator %3CString%3E keys = wpsParams.keys();%0A            while (keys.hasNext()) %7B%0A                String key = keys.next();%0A                if (%22no_data%22.equals(key)) %7B%0A                    data.put(%22noDataValue%22, wpsParams.optInt(key, -1));%0A                %7D else if (%22join_key%22.equals(key)) %7B%0A                    data.putOpt(%22commonId%22, wpsParams.optString(key, null));%0A                %7D else if (%22input_type%22.equals(key)) %7B%0A                    data.putOpt(%22wpsType%22, wpsParams.optString(key, null));%0A                %7D else %7B%0A                    // if wps params has additional keys, store them%0A                    data.put(key, wpsParams.get(key));%0A                %7D%0A            %7D%0A
 %0A   

migrate wps params to attributes.data