/*
 * 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.apache.flume.serialization;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.Set;

import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.conf.Configurable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class simply writes the body of the event to the output stream
 * and appends a newline after each event.
 */
public class BodyTextEventSerializer implements EventSerializer, Configurable {

  private final static Logger logger =
      LoggerFactory.getLogger(BodyTextEventSerializer.class);

  private final OutputStream out;

  private BodyTextEventSerializer(OutputStream out) {
    this.out = out;
  }

  @Override
  public void configure(Context context) {
    // noop
  }

  @Override
  public boolean supportsReopen() {
    return true;
  }

  @Override
  public void afterCreate() {
    // noop
  }

  @Override
  public void afterReopen() {
    // noop
  }

  @Override
  public void beforeClose() {
    // noop
  }

  @Override
  public void write(Event e) throws IOException {
	  Map<String, String> mapHeader = e.getHeaders();
	  Set<String> keySet =mapHeader.keySet();
	  for(String key: keySet){
		  String value = mapHeader.get(key);
		  String keyValue ="***** ------"+key+"	:	 "+value;
		  out.write(keyValue.getBytes());
		  out.write('\n');
	  }
    out.write(e.getBody());
    out.write('\n');
  }

  @Override
  public void flush() throws IOException {
    // noop
  }

  public static class Builder implements EventSerializer.Builder {

    @Override
    public EventSerializer build(Context context, OutputStream out) {
      BodyTextEventSerializer s = new BodyTextEventSerializer(out);
      s.configure(context);
      return s;
    }

  }

}
