package com.fshark.overseas.advert.sink.server;


import com.fshark.overseas.advert.entity.dao.MetricsDao;
import com.fshark.overseas.advert.modle.metrics.ServerActivationMetrics;
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 ServerActivationSink extends RichSinkFunction<ServerActivationMetrics> {

    private AppConfig appConfig;

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

    private JdbiContext jdbiContext;

    private MetricsDao metricsDao;

    @Override
    public void invoke(ServerActivationMetrics value, Context context) throws Exception {
        super.invoke(value, context);
        if (value.getData_active_day_dau() + value.getData_register() + value.getData_day_register_create() + value.getData_create_role() > 0) {
            metricsDao.updateServerActivationMetrics(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();
        }
    }
}
