package com.tsi.comm.consumer;

import com.tsi.comm.consumer.kafka.KafkaConsumerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Slf4j
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class TsiCommConsumerApplication implements ApplicationRunner, ApplicationListener<ContextClosedEvent> {

    private static String bootstrapServers = "172.24.0.30:9092,172.24.0.31:9093,172.24.0.32:9094";
    private static String topic = "node";
    private static String consumerGroup = "tsi-consumer";
    private static String nodeId = "";

    private KafkaConsumerService kafkaConsumerService = null;

    // java -jar tsi-consumer.jar --servers=172.24.0.30:9092,172.24.0.31:9093,172.24.0.32:9094 --topic=node --group=tsi-consumer1 --key=4060000101,4060000112
    public static void main(String[] args) {
        SpringApplication application = new SpringApplicationBuilder()
                .sources(TsiCommConsumerApplication.class)
                .build();
        application.setBannerMode(Banner.Mode.OFF);
        application.run(args);
//        SpringApplication.run(TsiCommConsumerApplication.class, args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
//        boolean debug = args.containsOption("debug");
//        List<String> files = args.getNonOptionArgs();
//        String[] sourceArgs = args.getSourceArgs();
//        List<String> nonOptionArgs = args.getNonOptionArgs();
        Set<String> optionNames = args.getOptionNames();

//        log.error("sourceArgs: {}", sourceArgs);
        boolean helpOptions = args.containsOption("help");
        if (helpOptions) {
            usage();
            return;
        }

        boolean nodeOptions = args.containsOption("key");
        if (!nodeOptions) {
            log.error("****** key options are required.");
            usage();
            return;
        }

        for (String optionName : optionNames) {
            List<String> optionValues = args.getOptionValues(optionName);
            for (String optionValue : optionValues) {
                if ("key".equals(optionName)) {
                    nodeId = optionValue;
                }
                else if ("servers".equals(optionName)) {
                    bootstrapServers = optionValue;
                }
                else if ("topic".equals(optionName)) {
                    topic = optionValue;
                }
                else if ("group".equals(optionName)) {
                    consumerGroup = optionValue;
                }
            }
        }

        List<String> keyValues = new ArrayList<>();
        String[] nodeIds = nodeId.split(",");
        for (int ii = 0; ii < nodeIds.length; ii++) {
            String node = nodeIds[ii].trim();
            if (node.isEmpty()) {
                continue;
            }
            keyValues.add(node);
        }
        if (keyValues.isEmpty()) {
            log.error("****** key options are required(all input data is blank).");
            usage();
            return;
        }

        if (!"node".equals(topic) && !"test".equals(topic) && !"cvim".equals(topic)) {
            usage();
            return;
        }
        kafkaConsumerService = new KafkaConsumerService(bootstrapServers, topic, consumerGroup, keyValues);
        kafkaConsumerService.start();
    }

    private void usage() {
        log.info("\r\n\n\n\n\nUsage: java -jar tsi-consumer --servers=xxx.xxx.xxx.xxx:nnnn --topic=node --group:tsi-consumer --key=4060000101\n" +
                "   --servers=kafka bootstrap server[optional, default=172.24.0.30:9092,172.24.0.31:9093,172.24.0.32:9094]\n" +
                "   --topic=topic name[optional, node/test/cvim, default=node]\n" +
                "   --group=kafka consumer group name[optional, default=tsi-consumer]\n" +
                "   --key=node id\n\n\n\n");
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            if (kafkaConsumerService != null) {
                kafkaConsumerService.shutdown();
            }
        } catch (Exception e) {
            log.error("{}", e.getMessage());
        }
        log.error("Application Terminated: {}, {}", sdfDate.format(new Date()), event);
    }
}
