/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.frameworkset.elasticsearch;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;
import java.util.Properties;

import org.elasticsearch.common.collect.MapBuilder;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.frameworkset.elasticsearch.event.Event;

import com.frameworkset.util.SimpleStringUtil;

/**
 * Serialize flume events into the same format LogStash uses</p>
 *
 * This can be used to send events to ElasticSearch and use clients such as
 * Kabana which expect Logstash formated indexes
 *
 * <pre>
 * {
 *    "@timestamp": "2010-12-21T21:48:33.309258Z",
 *    "@tags": [ "array", "of", "tags" ],
 *    "@type": "string",
 *    "@source": "source of the event, usually a URL."
 *    "@source_host": ""
 *    "@source_path": ""
 *    "@fields":{
 *       # a set of fields for this event
 *       "user": "jordan",
 *       "command": "shutdown -r":
 *     }
 *     "@message": "the original plain-text message"
 *   }
 * </pre>
 *
 * If the following headers are present, they will map to the above logstash
 * output as long as the logstash fields are not already present.</p>
 *
 * <pre>
 *  timestamp: long -> @timestamp:Date
 *  host: String -> @source_host: String
 *  src_path: String -> @source_path: String
 *  type: String -> @type: String
 *  source: String -> @source: String
 * </pre>
 *
 * https
 *      ://github.com/logstash/logstash/wiki/logstash%27s-internal-message-
 *      format
 */
public class ElasticSearchLogStashEventSerializer implements
    ElasticSearchEventSerializer {

  @Override
  public  XContentBuilder getContentBuilder(Event event) throws IOException {
    XContentBuilder builder = jsonBuilder();

      builder.startObject();
      appendBody(builder, event);
      appendHeaders(builder, event);
      builder.endObject();
      return builder;



  }

  private   void appendBody(XContentBuilder builder, Event event)
      throws IOException, UnsupportedEncodingException {
    byte[] body = (byte[]) event.getBody();
    ContentBuilderUtil.appendField(builder, "@message", body);

  }

  private  void appendHeaders(XContentBuilder builder, Event event)
      throws IOException {
//    Map<String, String> headers = Maps.newHashMap(event.getHeaders());
	  MapBuilder mapBuilder = MapBuilder.newMapBuilder();
//	  mapBuilder.putAll(event.getHeaders());
//	  Map<String, String> headers = mapBuilder.map();
    Map<String, String> headers = event.getHeaders();
    if(headers == null || headers.size() == 0){
      return;
    }
    String timestamp = headers.remove("timestamp");
    if (!SimpleStringUtil.isEmpty(timestamp)
        && SimpleStringUtil.isEmpty(headers.get("@timestamp"))) {
      long timestampMs = Long.parseLong(timestamp);
      builder.field("@timestamp", new Date(timestampMs));
    }

    String source = headers.remove("source");
    if (!SimpleStringUtil.isEmpty(source)
        && SimpleStringUtil.isEmpty(headers.get("@source"))) {
      ContentBuilderUtil.appendField(builder, "@source",
          source.getBytes(charset));
    }

    String type = headers.remove("type");
    if (!SimpleStringUtil.isEmpty(type)
        && SimpleStringUtil.isEmpty(headers.get("@type"))) {
      ContentBuilderUtil.appendField(builder, "@type", type.getBytes(charset));
    }

    String host = headers.remove("host");
    if (!SimpleStringUtil.isEmpty(host)
        && SimpleStringUtil.isEmpty(headers.get("@source_host"))) {
      ContentBuilderUtil.appendField(builder, "@source_host",
          host.getBytes(charset));
    }

    String srcPath = headers.remove("src_path");
    if (!SimpleStringUtil.isEmpty(srcPath)
        && SimpleStringUtil.isEmpty(headers.get("@source_path"))) {
      ContentBuilderUtil.appendField(builder, "@source_path",
          srcPath.getBytes(charset));
    }

    builder.startObject("@fields");
    for (String key : headers.keySet()) {
      byte[] val = headers.get(key).getBytes(charset);
      ContentBuilderUtil.appendField(builder, key, val);
    }
    builder.endObject();
  }

  
  public void configure(Properties elasticsearchPropes) {
    // NO-OP...
  }
 
}
