package com.fshark.overseas.advert.sink;


import com.fshark.overseas.advert.entity.dao.MetricsDao;
import com.fshark.overseas.advert.modle.metrics.ActivationMetrics;
import com.fshark.overseas.advert.util.AppConfig;
import com.fshark.overseas.advert.util.Constants;
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.sink.RichSinkFunction;

public class ActicitionSink extends RichSinkFunction<ActivationMetrics> {

    private AppConfig appConfig;

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

    private JdbiContext jdbiContext;

    private MetricsDao metricsDao;

    @Override
    public void invoke(ActivationMetrics value, Context context) throws Exception {
        super.invoke(value, context);
        if (value.getData_activation() + value.getData_register() + value.getData_device_register() + value.getData_create_role() + value.getData_day_act_register() + value.getData_day_register_create() + value.getData_active_day_dau() > 0) {
            metricsDao.insertActivationMetrics(value);
        }
        if (value.getData_register() > 0){
            metricsDao.insertRegisterNum(value);
        }
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        super.open(parameters);
        if (appConfig.getSinkType().equals(Constants.TYPE_SINK)){
            jdbiContext = DatabaseUtils.getGenJdbiClient(appConfig.getDbHost(), appConfig.getDbUser(), appConfig.getDbPassword());
        } else {
            jdbiContext = DatabaseUtils.getCHGenJdbiClient(appConfig.getDbHost(), appConfig.getDbUser(), appConfig.getDbPassword());
        }
        metricsDao = jdbiContext.getJdbi().onDemand(MetricsDao.class);
    }

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