/*
 * Copyright (C) 2011 Benoit GUEROUT <bguerout at gmail dot com> and Yves AMSELLEM <amsellem dot yves at gmail dot com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jongo.query;

import com.mongodb.DBObject;
import com.mongodb.util.JSON;
import org.jongo.bson.Bson;
import org.jongo.marshall.Marshaller;
import org.jongo.marshall.MarshallingException;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class JsonQueryFactory implements QueryFactory {

    private static final String DEFAULT_TOKEN = "#";
    private final String token;
    private final Marshaller marshaller;
    private final Pattern pattern;

    public JsonQueryFactory(Marshaller marshaller) {
        this(marshaller, DEFAULT_TOKEN);
    }

    public JsonQueryFactory(Marshaller marshaller, String token) {
        this.marshaller = marshaller;
        this.token = token;
        this.pattern = Pattern.compile(token);
    }

    public final Query createQuery(String query, Object... parameters) {

        if (parameters.length == 0) {
            return new JsonQuery(query);
        }
        return createQueryWithParameters(query, parameters);
    }

    private JsonQuery createQueryWithParameters(String template, Object[] parameters) {
        String query = template;
        assertThatParamsCanBeBound(query, parameters);
        int paramIndex = 0;
        while (query.contains(token)) {
            Object parameter = parameters[paramIndex++];
            query = bindParameter(query, parameter);
        }
        return new JsonQuery(query);
    }

    private String bindParameter(String query, Object parameter) {
        try {
            String jsonParam = marshallParameter(parameter).toString();
            return query.replaceFirst(token, getMatcherWithEscapedDollar(jsonParam));
        } catch (RuntimeException e) {
            String message = String.format("Unable to bind parameter: %s into query: %s", parameter, query);
            throw new IllegalArgumentException(message, e);
        }
    }

    private Object marshallParameter(Object parameter) {
        try {
            if (Bson.isPrimitive(parameter)) {
                return JSON.serialize(parameter);
            }
            if (parameter instanceof Enum) {
                return JSON.serialize(((Enum) parameter).name());
            }
            if (parameter instanceof List) {
                return marshallArray(((List) parameter).toArray());
            }
            if (parameter instanceof Object[]) {
                return marshallArray((Object[]) parameter);
            }
            return marshallDocument(parameter);
        } catch (Exception e) {
            String message = String.format("Unable to marshall parameter: %s", parameter);
            throw new MarshallingException(message, e);
        }
    }

    private List<Object> marshallArray(Object[] parameters) {
        List<Object> newParameterList = new ArrayList<Object>();
        for (Object param : parameters) {
            newParameterList.add(marshallParameter(param));
        }
        return newParameterList;
    }

    private DBObject marshallDocument(Object parameter) {
        return marshaller.marshall(parameter).toDBObject();
    }

    private void assertThatParamsCanBeBound(String template, Object[] parameters) {
        int nbTokens = countTokens(template);
        if (nbTokens != parameters.length) {
            String message = String.format("Unable to bind parameters into query: %s. Tokens and parameters numbers mismatch " +
                    "[tokens: %s / parameters:%s]", template, nbTokens, parameters.length);
            throw new IllegalArgumentException(message);
        }
    }

    /**
     * http://veerasundar.com/blog/2010/01/java-lang-illegalargumentexception-illegal-group-reference-in-string-replaceall/
     */
    private String getMatcherWithEscapedDollar(String serialized) {
        return Matcher.quoteReplacement(serialized);
    }

    private int countTokens(String template) {
        int count = 0;
        Matcher matcher = pattern.matcher(template);
        while (matcher.find()) {
            count++;
        }
        return count;
    }

}

@@ -901,20 +901,17 @@
 il.Array
-List
+s
 ;%0Aimport
@@ -3421,28 +3421,22 @@
 private 
-List%3CObject%3E
+String
  marshal
@@ -3477,140 +3477,131 @@
     
-List%3C
 Object
-%3E newParameterList = new ArrayList%3CObject%3E();%0A        for (Object param : parameters) %7B%0A            newParameterList.add(
+%5B%5D list = new Object%5Bparameters.length%5D;%0A        for (int i = 0; i %3C parameters.length; i++) %7B%0A            list%5Bi%5D = 
 mars
@@ -3615,25 +3615,32 @@
 ameter(param
-)
+eters%5Bi%5D
 );%0A        %7D
@@ -3659,24 +3659,29 @@
 urn 
-newParameterL
+Arrays.toString(l
 ist
+)
 ;%0A  

Fix ugly toString during Array Marshalling