/*
 * Copyright 2015 Data Artisans GmbH
 *
 * 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 com.dataartisans.flink.dataflow.io;

import com.google.cloud.dataflow.sdk.transforms.PTransform;
import com.google.cloud.dataflow.sdk.values.PCollection;
import com.google.cloud.dataflow.sdk.values.PDone;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;

/**
 * Transform for printing the contents of a {@link com.google.cloud.dataflow.sdk.values.PCollection}.
 * to standard output.
 *
 * This is Flink-specific and will only work when executed using the
 * {@link com.dataartisans.flink.dataflow.FlinkPipelineRunner}.
 */
public class KafkaIO {

	/**
	 * A PTransform that writes a PCollection to a standard output.
	 */
	public static class Write {

		/**
		 * Returns a KafkaIO.Write PTransform with the given step name.
		 */
		public static Bound<String> named(String name) {
			return new Bound<String>().named(name);
		}

		public static Bound<String> to(FlinkKafkaProducer kafkaProducer) {
			return new Bound<String>().to(kafkaProducer);
		}

		/**
		 * A PTransform that writes a bounded PCollection to standard output.
		 */
		public static class Bound<T> extends PTransform<PCollection<T>, PDone> {
			private static final long serialVersionUID = 0;

			private final FlinkKafkaProducer kafkaProducer;

			Bound() {
				this("KafkaIO.Write", null);
			}

			public Bound(String name, FlinkKafkaProducer kafkaProducer) {
				super(name);
				this.kafkaProducer = kafkaProducer;
			}

			/**
			 * Returns a new KafkaIO.Write PTransform that's like this one but with the given
			 * step
			 * name.  Does not modify this object.
			 */
			public Bound<T> named(String name) {
				return new Bound<>(name, kafkaProducer);
			}

			public Bound<T> to(FlinkKafkaProducer filenamePrefix) {
				return new Bound<>(name, kafkaProducer);
			}

			@Override
			public PDone apply(PCollection<T> input) {
				return PDone.in(input.getPipeline());
			}

			public FlinkKafkaProducer getKafkaProducer() {
				return kafkaProducer;
			}

		}
	}
}

