/*
 * Copyright 2022 Google LLC
 *
 * 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
 *
 *     https://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 kafka;

import org.apache.beam.runners.dataflow.options.DataflowPipelineOptions;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.io.kafka.KafkaIO;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.values.KV;
import org.apache.kafka.common.serialization.IntegerSerializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.List;

public class WriteKafka {

    private static final Logger LOG = LoggerFactory.getLogger(WriteKafka.class);

    public interface WriteKafkaOptions extends DataflowPipelineOptions {
        @Description("Kafka Bootstrap")
        String getBootstrap();

        void setBootstrap(String value);

        @Description("Kafka Topic")
        String getTopic();

        void setTopic(String value);
    }

    public static void main(String[] args) {
        WriteKafkaOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().as(WriteKafkaOptions.class);

        Pipeline p = Pipeline.create(options);

        final List<KV<Integer, String>> elements = Arrays.asList(
                KV.of(2, "this"),
                KV.of(3, "is"),
                KV.of(5, "a"),
                KV.of(7, "Kafka"),
                KV.of(11, "message"),
                KV.of(13, "from"),
                KV.of(17, "Dataflow")
        );

        p
                .apply(Create.of(elements))
                .apply(KafkaIO.<Integer, String>write()
                        .withBootstrapServers(options.getBootstrap())
                        .withTopic(options.getTopic())
                        .withValueSerializer(StringSerializer.class)
                        .withKeySerializer(IntegerSerializer.class)
                );


        p.run();
    }
}
