package me.berezovskyi.aws.testlambda;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;

import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.lambda.runtime.Context;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class StreamHandler {
	
	static DynamoDB dynamoDB = new DynamoDB(Regions.EU_WEST_1);
	
	public static void handler(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
    	String input = IOUtils.toString(inputStream);
    	context.getLogger().log("Input: " + input);
    	IOUtils.write(input, outputStream);    
    	
    	JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(input);
        if (element.isJsonObject()) {
            JsonObject req = element.getAsJsonObject();
            String operation = req.get("operation").getAsString();
            String tableName = req.get("tableName").getAsString(); // TODO if exists
            
            Table table = dynamoDB.getTable(tableName);
            
            JsonObject payload = req.get("payload").getAsJsonObject();
            
            if(operation == "create") {
            	table.putItem(Item.fromJSON(payload.toString())); //let's see how bad does it go
            }
            
//            JsonArray datasets = operation.getAsJsonArray("dataset");
//            for (int i = 0; i < datasets.size(); i++) {
//                JsonObject dataset = datasets.get(i).getAsJsonObject();
//                System.out.println(dataset.get("album_title").getAsString());
//            }
        }
    }
}

@@ -1243,16 +1243,17 @@
 tring();
+ 
  // TODO
@@ -1263,16 +1263,16 @@
  exists%0A
-
         
@@ -1535,353 +1535,36 @@
 )));
+ 
  //
-let's see how bad does it go%0A            %7D%0A            %0A//            JsonArray datasets = operation.getAsJsonArray(%22dataset%22);%0A//            for (int i = 0; i %3C datasets.size(); i++) %7B%0A//                JsonObject dataset = datasets.get(i).getAsJsonObject();%0A//                System.out.println(dataset.get(%22album_title%22).getAsString());%0A//
+ how bad can it be? %7D:)%0A
     

remove JSON boilerplate