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


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

    private AppConfig appConfig;

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

    private JdbiContext jdbiContext;

    private MetricsDao metricsDao;

    @Override
    public void invoke(ServerRemainMetrics value, Context context) throws Exception {
        super.invoke(value, context);
        //短线留存
        Long days = value.getDays();
        if (days == 2 || days == 3 || days == 7 || days == 15 || days == 30) {
            String column = "data_active_" + days + "day";
            jdbiContext.getJdbi().withHandle(handle -> {

                String sql = String.format("insert into appsflyer_metrics_server" +
                                " (`data_date`,`data_hour`,`time_zone`,`region`, `platform`, `game_id`, `media_source`, `campaign_id` ,`ad_set_id`,`ad_id`,`channel`,`server_id`,`%s`)" +
                                " values ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s') ",
                        column, value.getData_date(), value.getData_hour(), value.getTime_zone(), value.getRegion(), value.getPlatform(), value.getGame_id(), value.getMedia_source(), value.getCampaign_id()
                        , value.getAd_set_id(), value.getAd_id(), value.getChannel(), value.getServer_id(), value.getUser_num(), column, column, column
                );
                handle.createUpdate(sql).execute();
                return null;
            });
        }

    }

    @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();
        }
    }
}
