package com.fshark.overseas.advert.sink;



import com.fshark.overseas.advert.entity.dao.EventInfoDao;
import com.fshark.overseas.advert.modle.SinkMetricEvent;
import com.fshark.overseas.advert.modle.metrics.EventMetrics;
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;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

public class EventTimesSink extends RichSinkFunction<SinkMetricEvent> {
    private AppConfig appConfig;
    public EventTimesSink(AppConfig appConfig) {
        this.appConfig = appConfig;
    }

    private JdbiContext jdbiContext;

    private EventInfoDao eventInfoDao;

    @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());
        }
        eventInfoDao = jdbiContext.getJdbi().onDemand(EventInfoDao.class);

    }

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

    @Override
    public void invoke(SinkMetricEvent value, Context context) throws Exception {
        super.invoke(value, context);
        if (value.isEvent()){
            eventInfoDao.insertEventTimes(value.getEventMetrics());
        }
    }
}
