/*
 * 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;

import com.mongodb.DBObject;
import com.mongodb.WriteConcern;
import org.fest.assertions.Condition;
import org.jongo.util.DBObjectResultHandler;
import org.jongo.util.JongoTestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

import static org.fest.assertions.Assertions.assertThat;

public class CommandTest extends JongoTestCase {

    private Jongo jongo;
    private MongoCollection collection;

    @Before
    public void setUp() throws Exception {
        jongo = getJongo();
        collection = createEmptyCollection("friends");
    }

    @After
    public void tearDown() throws Exception {
        dropCollection("friends");
    }

    @Test
    public void canRunACommand() throws Exception {
        DBObject result = jongo.runCommand("{ serverStatus: 1 }").map(new DBObjectResultHandler());

        assertThat(result).isNotNull();
        assertThat(result.get("version")).isNotNull();
        assertThat(result.get("ok")).isEqualTo(1.0);
    }

    @Test
    public void canRunACommandWithParameter() throws Exception {

        collection.withConcern(WriteConcern.SAFE).insert("{test:1}");

        DBObject result = jongo.runCommand("{ count: #}", "friends").map(new DBObjectResultHandler());

        assertThat(result.get("n")).isEqualTo(1.0);
    }

    @Test
    public void canRunAGeoNearCommand() throws Exception {

        MongoCollection safeCollection = collection.withConcern(WriteConcern.SAFE);
        safeCollection.insert("{loc:{lat:48.690833,lng:9.140556}}");
        safeCollection.ensureIndex("{loc:'2d'}");

        DBObject command = jongo.runCommand("{ geoNear : 'friends', near : [48.690,9.140], spherical: true}")
                .throwOnError()
                .map(new DBObjectResultHandler());

        DBObject results = (DBObject) command.get("results");
        assertThat(results).isNotNull();
        DBObject obj = (DBObject) results.get("0");
        assertThat(obj.get("dis")).satisfies(new Condition<Object>() {
            @Override
            public boolean matches(Object value) {
                return value instanceof Double && ((Double) value) > 1.7E-5 && ((Double) value) < 1.8E-5;
            }
        });
    }

    @Test
    public void canRunACommandAs() throws Exception {
        ServerStatus status = jongo.runCommand("{ serverStatus: 1 }").as(ServerStatus.class);

        assertThat(status.host).isNotNull();
        assertThat(status.ok).isEqualTo("1.0");
    }

    @Test
    public void canRunInvalidCommand() throws Exception {
        ServerStatus status = jongo.runCommand("{forceerror:1}").as(ServerStatus.class);

        assertThat(status.ok).isEqualTo("0.0");
    }

    @Test
    public void canThrowExceptionOnInvalidCommand() throws Exception {
        try {
            jongo.runCommand("{forceerror:1}").throwOnError().as(ServerStatus.class);
        } catch (RuntimeException e) {
            assertThat(e.getMessage()).contains("forced error");
        }
    }

    private static class ServerStatus {
        String ok, host;
    }


    private static class Location {
        double dis;
    }
}

@@ -699,16 +699,70 @@
 jongo;%0A%0A
+import com.fasterxml.jackson.annotation.JsonProperty;%0A
 import c
@@ -2296,16 +2296,30 @@
 .140556%7D
+, name:'Paris'
 %7D%22);%0A   
@@ -2378,24 +2378,35 @@
     
-DBObject command
+GeoNearResult geoNearResult
  = j
@@ -2540,195 +2540,142 @@
    .
-map(new DBObjectResultHandler());%0A%0A        DBObject results = (DBObject) command.get(%22results%22);%0A        assertThat(results).isNotNull();%0A        DBObject obj = (DBObject) results.get(%220%22
+as(GeoNearResult.class);%0A%0A        List%3CLocation%3E locations = geoNearResult.locations;%0A        assertThat(locations.size()).isEqualTo(1
 );%0A 
@@ -2696,22 +2696,28 @@
 hat(
-obj
+locations
 .get(
-%22
+0).
 dis
-%22)
 ).sa
@@ -2738,22 +2738,22 @@
 ndition%3C
-Object
+Double
 %3E() %7B%0A  
@@ -2807,22 +2807,22 @@
 matches(
-Object
+Double
  value) 
@@ -2872,33 +2872,22 @@
 ouble &&
- ((Double)
  value
-)
  %3E 1.7E-
@@ -2894,25 +2894,14 @@
 5 &&
- ((Double)
  value
-)
  %3C 1
@@ -2933,16 +2933,83 @@
     %7D);%0A
+        assertThat(locations.get(0).getName()).isEqualTo(%22Paris%22);%0A
     %7D%0A%0A 
@@ -3509,24 +3509,35 @@
 oid 
-canThrowExceptio
+mustForceExceptionToBeThrow
 nOnI
@@ -3864,16 +3864,130 @@
 %0A    %7D%0A%0A
+    private static class GeoNearResult %7B%0A        @JsonProperty(%22results%22)%0A        List%3CLocation%3E locations;%0A    %7D%0A
 %0A    pri
@@ -4011,24 +4011,25 @@
  Location %7B%0A
+%0A
         doub
@@ -4039,13 +4039,473 @@
 dis;
+%0A%0A        /**%0A         * Real Location document is contained into 'obj' property%0A         * Jackson doesn't support nested mapping. see http://jira.codehaus.org/browse/JACKSON-781%0A         */%0A        @JsonProperty(%22obj%22)%0A        NestedLocation nestedLocation;%0A%0A        public String getName() %7B%0A            return nestedLocation.locationName;%0A        %7D%0A    %7D%0A%0A    private static class NestedLocation %7B%0A        @JsonProperty(%22name%22)%0A        String locationName;
 %0A    %7D%0A%7D
 %0A
@@ -4503,9 +4503,8 @@
 %0A    %7D%0A%7D
-%0A

Use jackson to unmarshall geoNear command