/*
 * 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.Arrays;
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 String marshallArray(Object[] parameters) {
        Object[] list = new Object[parameters.length];
        for (int i = 0; i < parameters.length; i++) {
            list[i] = marshallParameter(parameters[i]);
        }
        return Arrays.toString(list);
    }

    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;
    }

}

@@ -705,16 +705,48 @@
 query;%0A%0A
+import com.mongodb.BasicDBList;%0A
 import c
@@ -2311,24 +2311,30 @@
 er(parameter
+, true
 ).toString()
@@ -2691,32 +2691,65 @@
 Object parameter
+, boolean serializeBsonPrimitives
 ) %7B%0A        try 
@@ -2811,32 +2811,58 @@
           return
+ serializeBsonPrimitives ?
  JSON.serialize(
@@ -2863,32 +2863,44 @@
 alize(parameter)
+ : parameter
 ;%0A            %7D%0A
@@ -2964,30 +2964,22 @@
     
-return JSON.serialize(
+String name = 
 ((En
@@ -2999,17 +2999,94 @@
 ).name()
-)
+;%0A                return serializeBsonPrimitives ? JSON.serialize(name) : name
 ;%0A      
@@ -3599,22 +3599,24 @@
 private 
-String
+DBObject
  marshal
@@ -3653,24 +3653,27 @@
         
-Object%5B%5D
+BasicDBList
  list = 
@@ -3680,33 +3680,21 @@
 new 
-Object%5Bparameters.length%5D
+BasicDBList()
 ;%0A  
@@ -3765,13 +3765,15 @@
 list
-%5Bi%5D =
+.put(i,
  mar
@@ -3800,16 +3800,24 @@
 eters%5Bi%5D
+, false)
 );%0A     
@@ -3840,29 +3840,12 @@
 urn 
-Arrays.toString(
 list
-)
 ;%0A  

Replace weak Arrays.toString() by BasicDBList