package com.fshark.overseas.advert.processor;

import com.fshark.overseas.advert.entity.dao.MetricsDetailDao;
import com.fshark.overseas.advert.modle.metrics.ActivationMetrics;
import com.fshark.overseas.advert.util.AppConfig;
import com.fshark.overseas.advert.util.DatabaseUtils;
import com.fshark.overseas.advert.util.JdbiContext;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.checkerframework.checker.units.qual.C;

public class StoreMetricProcess extends ProcessAllWindowFunction<ActivationMetrics, Object, TimeWindow> {

    private AppConfig appConfig;

    private JdbiContext jdbiContext;
    private MetricsDetailDao metricsDetailDao;


    public StoreMetricProcess(AppConfig appConfig) {
        this.appConfig = appConfig;
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        super.open(parameters);
        jdbiContext = DatabaseUtils.getCHGenJdbiClient(appConfig.getDbHost(), appConfig.getDbUser(), appConfig.getDbPassword());
        metricsDetailDao = jdbiContext.getJdbi().onDemand(MetricsDetailDao.class);

    }

    @Override
    public void process(Context context, Iterable<ActivationMetrics> elements, Collector<Object> out) throws Exception {
        for (ActivationMetrics element : elements) {
            if (element.getData_activation() > 0) {
                metricsDetailDao.insertMetricDetail(element, "data_activation");
            }

            if (element.getData_register() > 0) {
                metricsDetailDao.insertMetricDetail(element, "data_register");
            }

            if (element.getData_device_register() > 0) {
                metricsDetailDao.insertMetricDetail(element, "data_device_register");
            }

            if (element.getData_create_role() > 0) {
                metricsDetailDao.insertMetricDetail(element, "data_create_role");
            }

            if (element.getData_day_act_register() > 0) {
                metricsDetailDao.insertMetricDetail(element, "data_day_act_register");
            }

            if (element.getData_day_register_create() > 0) {
                metricsDetailDao.insertMetricDetail(element, "data_day_register_create");
            }

            if (element.getData_active_day_dau() > 0) {
                metricsDetailDao.insertMetricDetail(element, "data_active_day_dau");
            }

            if (element.getDateRemind() > 0) {
                String column = "retention_day" + element.getDateRemind();
                metricsDetailDao.insertMetricDetail(element, column);
            }
        }

    }

    @Override
    public void close() throws Exception {
        super.close();
        if (jdbiContext != null) {
            jdbiContext.getDataSource().close();
        }
    }
}
