package com.fshark.overseas.advert.app;

import com.fshark.overseas.advert.modle.SinkMetricEvent;
import com.fshark.overseas.advert.modle.metrics.ActivationMetrics;
import com.fshark.overseas.advert.processor.*;
import com.fshark.overseas.advert.sink.EventTimesSinkProcess;
import com.fshark.overseas.advert.sink.PurchaseSink;
import com.fshark.overseas.advert.util.AppConfig;
import com.fshark.overseas.advert.util.Constants;
import com.google.gson.Gson;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.util.Collector;

import java.util.Properties;
import java.util.concurrent.TimeUnit;

public class AppsflyerMetricStore {
    static AppConfig loadConfigFromArgs(String[] args) {
        ParameterTool parameters = ParameterTool.fromArgs(args);
        AppConfig appConfig = new AppConfig();
        try {
            appConfig.setSourceKafkaBootstrapServers(parameters.get("source-kafka-bootstrap-servers"));
            appConfig.setSourceKafkaGroupId(parameters.get("source-kafka-group-id"));
            appConfig.setSourceKafkaTopic(parameters.get("source-kafka-topic"));

            appConfig.setDbHost(parameters.get("jdbc-host"));
            appConfig.setDbUser(parameters.get("jdbc-user"));
            appConfig.setDbPassword(parameters.get("jdbc-password"));

            appConfig.setSinkType(parameters.get("sink-type"));

        } catch (Exception e) {
            System.err.println("Place set args: " +
                    " --source-kafka-bootstrap-servers <source-kafka-bootstrap-servers>" +
                    " --source-kafka-group-id <source-kafka-group-id>" +
                    " --source-kafka-topic <source-kafka-topic>" +
                    " --jdbc-host <jdbc-host> " +
                    " --jdbc-user <jdbc-user> " +
                    " --jdbc-password <jdbc-password> " +
                    " --sink-type <sink-type>");
            throw e;
        }
        return appConfig;
    }

    public static void main(String[] args) throws Exception {
        AppConfig appConfig = loadConfigFromArgs(args);
        final StreamExecutionEnvironment sse = StreamExecutionEnvironment.getExecutionEnvironment();
        sse.setParallelism(1);
        sse.enableCheckpointing(1000 * 60 * 10);
        sse.setRestartStrategy(RestartStrategies.fixedDelayRestart(Integer.MAX_VALUE, org.apache.flink.api.common.time.Time.of(10, TimeUnit.SECONDS)));

        //source设置
        Properties properties = new Properties();
        properties.setProperty("bootstrap.servers", appConfig.getSourceKafkaBootstrapServers());
        properties.setProperty("group.id", appConfig.getSourceKafkaGroupId());
        properties.setProperty("auto.offset.reset", "latest");
        FlinkKafkaConsumer<String> dataConsumer = new FlinkKafkaConsumer<>(appConfig.getSourceKafkaTopic(), new SimpleStringSchema(), properties);

        DataStream<SinkMetricEvent> activationMetricsDataStream = sse.addSource(dataConsumer)
                .flatMap(new RichFlatMapFunction<String, SinkMetricEvent>() {
                    @Override
                    public void flatMap(String value, Collector<SinkMetricEvent> out) throws Exception {
                        out.collect(new Gson().fromJson(value, SinkMetricEvent.class));
                    }
                })
                .uid("parse-event")
                .name("parse-event");

        /**
         * afid 指标写入
         */
        activationMetricsDataStream
                .flatMap(new MetricJsonToObProcessor())
                .windowAll(TumblingProcessingTimeWindows.of(Time.seconds(5)))
                .process(new StoreMetricProcess(appConfig))
                .uid("metric-detail")
                .name("metric-detail");

        /**
         * ouid 指标写入
         */
        activationMetricsDataStream
                .flatMap(new RichFlatMapFunction<SinkMetricEvent, ActivationMetrics>() {
                    @Override
                    public void flatMap(SinkMetricEvent value, Collector<ActivationMetrics> out) throws Exception {
                        if (Constants.TYPE_SINK_OUID_METRIC.equals(value.getEventType()) && value.getEventData() != null) {
                            out.collect(value.getEventData());
                        }
                    }
                }).windowAll(TumblingProcessingTimeWindows.of(Time.seconds(5)))
                .process(new OuidStoreMetricProcess(appConfig))
                .uid("ouid-sink-event")
                .name("ouid-sink-event");


        //订单写入 包含ouid订单信息
        activationMetricsDataStream
                .filter(SinkMetricEvent::isOrderEvent)
                .addSink(new PurchaseSink(appConfig))
                .uid("order-sink-event")
                .name("order-sink-event");

//              角色注册激活写入  todo 废弃
//        activitionResult.addSink(new ActicitionSink(appConfig))
//                .uid("login-sink-event")
//                .name("login-sink-event");

//       留存写入  todo 废弃
//        activationMetricsDataStream
//                .flatMap(new RemainProcess())
//                .timeWindowAll(Time.seconds(30)).process()
//                .addSink(new RemainSink(appConfig))
//                .uid("remain-sink-event")
//                .name("remain-sink-event");


//
//
        //角色注册激活预聚合 todo 废弃
//        DataStream<ServerActivationMetrics> activationMetricsList = activationMetricsDataStream
//                .flatMap(new RichFlatMapFunction<SinkMetricEvent, ServerActivationMetrics>() {
//                    @Override
//                    public void flatMap(SinkMetricEvent value, Collector<ServerActivationMetrics> out) {
//                        if (value.isServer()) {
//                            out.collect(value.getServerActivationMetrics());
//                        }
//                    }
//                })
//                .keyBy(ServerActivationMetrics::getKey)
//                .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
//                .aggregate(new ServerActivationAggregateFunction(), new ServerActivationResultWindows())
//                .uid("server-activation-agg-event")
//                .name("server-activation-agg-event");
//
//        activationMetricsList.addSink(new ServerActivationSink(appConfig))
//                .uid("server-activationsink-event")
//                .name("server-activationsink-event");

        //留存预聚合 todo 废弃
//        DataStream<ServerRemainMetrics> remainMetrics = activationMetricsDataStream
//                .flatMap(new RichFlatMapFunction<SinkMetricEvent, ServerActivationMetrics>() {
//                    @Override
//                    public void flatMap(SinkMetricEvent value, Collector<ServerActivationMetrics> out) {
//                        if (value.isServer()) {
//                            out.collect(value.getServerActivationMetrics());
//                        }
//                    }
//                })
//                .flatMap(new ServerRemainProcessor(appConfig))
//                .keyBy(ServerRemainMetrics::getRemind_key)
//                .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
//                .sum("user_num")
//                .uid("server-remain-event")
//                .name("server-remain-event");
//        remainMetrics.addSink(new ServerRemindSink(appConfig))
//                .uid("server-remindsink-event")
//                .name("server-remindsink-event");

        /**
         * 事件写入
         */
        activationMetricsDataStream.filter(SinkMetricEvent::isEvent)
                .windowAll(TumblingProcessingTimeWindows.of(Time.seconds(5)))
                .process(new EventTimesSinkProcess(appConfig))
                .uid("event-sink-event")
                .name("event-sink-event");

        sse.execute("Appsflyer-Store-analyze");
    }
}
