/*
 * Copyright © 2015 Cask Data, Inc.
 *
 * 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 co.cask.plugin.etl.batch.sink;

import co.cask.cdap.api.annotation.Description;
import co.cask.cdap.api.annotation.Name;
import co.cask.cdap.api.annotation.Plugin;
import co.cask.cdap.api.data.batch.OutputFormatProvider;
import co.cask.cdap.api.data.format.StructuredRecord;
import co.cask.cdap.api.data.schema.Schema;
import co.cask.cdap.api.dataset.lib.KeyValue;
import co.cask.cdap.api.plugin.PluginConfig;
import co.cask.cdap.etl.api.Emitter;
import co.cask.cdap.etl.api.batch.BatchSink;
import co.cask.cdap.etl.api.batch.BatchSinkContext;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.hadoop.MongoOutputFormat;
import com.mongodb.hadoop.io.BSONWritable;
import org.apache.hadoop.io.NullWritable;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;

/**
 * A {@link BatchSink} that writes data to MongoDB.
 * This {@link MongoDBBatchSink} takes a {@link StructuredRecord} in,
 * converts it to {@link BSONWritable}, and writes it to MongoDB.
 */
@Plugin(type = "batchsink")
@Name("MongoDB")
@Description("CDAP MongoDB Batch Sink converts {@link StructuredRecord} to {@link BSONWritable} and writes to MongoDB")
public class MongoDBBatchSink extends BatchSink<StructuredRecord, NullWritable, BSONWritable> {

  private final MongoDBSinkConfig config;

  public MongoDBBatchSink(MongoDBSinkConfig config) {
    this.config = config;
  }

  @Override
  public void prepareRun(BatchSinkContext context) throws Exception {
    context.addOutput(Properties.CONNECTION_STRING, new MongoDBOutputFormatProvider(config));
  }

  @Override
  public void transform(StructuredRecord input, Emitter<KeyValue<NullWritable, BSONWritable>> emitter) throws Exception {
    BasicDBObjectBuilder bsonBuilder = BasicDBObjectBuilder.start();
    for (Schema.Field field : input.getSchema().getFields()) {
      bsonBuilder.add(field.getName(), input.get(field.getName()));
    }
    emitter.emit(new KeyValue<>(NullWritable.get(), new BSONWritable(bsonBuilder.get())));
  }

  private static class MongoDBOutputFormatProvider implements OutputFormatProvider {
    private final Map<String, String> conf;

    public MongoDBOutputFormatProvider(MongoDBSinkConfig config) {
      this.conf = new HashMap<>();
      conf.put("mongo.output.uri", config.connectionString);
    }

    @Override
    public String getOutputFormatClassName() {
      return MongoOutputFormat.class.getName();
    }

    @Override
    public Map<String, String> getOutputFormatConfiguration() {
      return conf;
    }
  }

  public static class MongoDBSinkConfig extends PluginConfig {
    @Name(Properties.CONNECTION_STRING)
    @Description("MongoDB Connection String (http://docs.mongodb.org/manual/reference/connection-string);" +
      "Example : mongodb://10.23.123.43:27017/analytics.users")
    private String connectionString;

    @Name(Properties.ID_FIELD)
    @Nullable
    @Description("Optionally make one of the incoming fields as the id field")
    private String idField;
  }

  public static class Properties {
    public static final String CONNECTION_STRING = "connectionString";
    public static final String ID_FIELD = "idField";
  }
}

@@ -1657,13 +1657,8 @@
 on(%22
-CDAP 
 Mong
@@ -1681,22 +1681,17 @@
 onverts 
-%7B@link
+a
  Structu
@@ -1703,19 +1703,13 @@
 cord
-%7D
  to 
-%7B@link
+a
  BSO
@@ -1717,17 +1717,16 @@
 Writable
-%7D
  and wri
@@ -1729,16 +1729,19 @@
  writes 
+it 
 to Mongo
@@ -1742,16 +1742,17 @@
  MongoDB
+.
 %22)%0Apubli
@@ -3260,16 +3260,20 @@
 String (
+see 
 http://d
@@ -3324,16 +3324,17 @@
 string);
+ 
 %22 +%0A    
@@ -3343,19 +3343,19 @@
 %22Example
- 
 : 
+'
 mongodb:
@@ -3360,20 +3360,17 @@
 b://
-10.23.123.43
+localhost
 :270
@@ -3387,16 +3387,18 @@
 cs.users
+'.
 %22)%0A    p
@@ -3508,12 +3508,17 @@
 lly 
-make
+specifies
  one
@@ -3556,16 +3556,17 @@
 id field
+.
 %22)%0A    p

Update MongoDBBatchSink.java