package com.fshark.overseas.advert.sink;

import com.fshark.overseas.advert.entity.GameAccount;
import com.fshark.overseas.advert.entity.dao.GameAccountDao;
import com.fshark.overseas.advert.entity.dao.OrderDao;
import com.fshark.overseas.advert.modle.AppsFlyerEvent;
import com.fshark.overseas.advert.modle.AppsflyerPurchase;
import com.fshark.overseas.advert.modle.OrderData;
import com.fshark.overseas.advert.modle.SinkMetricEvent;
import com.fshark.overseas.advert.util.*;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import java.util.Optional;

public class PurchaseSink extends RichSinkFunction<SinkMetricEvent> {

    private AppConfig appConfig;

    private JdbiContext jdbiContext;
    private OrderDao orderDao;
    private GameAccountDao gameAccountDao;

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

    @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());
        }
        orderDao = jdbiContext.getJdbi().onDemand(OrderDao.class);
        gameAccountDao = jdbiContext.getJdbi().onDemand(GameAccountDao.class);
    }

    @Override
    public void invoke(SinkMetricEvent value, Context context) throws Exception {
        super.invoke(value, context);
        if (Constants.TYPE_SINK_ORDER.equals(value.getEventType())){
            OrderData eventData =  value.getOrderData();
            orderDao.insertOrder(eventData);
        }
    }


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

    }
}
