package com.fshark.overseas.advert.processor;


import com.fshark.overseas.advert.entity.dao.GameMappingDao;
import com.fshark.overseas.advert.modle.AppsFlyerEvent;
import com.fshark.overseas.advert.modle.PlatformEnum;
import com.fshark.overseas.advert.modle.mapping.AdMapping;
import com.fshark.overseas.advert.modle.mapping.Game;
import com.fshark.overseas.advert.modle.mapping.Media;
import com.fshark.overseas.advert.modle.mapping.MediaCampaign;
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.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.util.Collector;

import java.util.Optional;

/**
 * 更新游戏广告的映射
 */
public class GameAdMappingProcessor extends RichFlatMapFunction<AppsFlyerEvent, ActivationMetrics> {

    private MapStateDescriptor<String, Game> stateDescriptor = new MapStateDescriptor("game_list_state", String.class, Game.class);

    private MapStateDescriptor<String, Media> mediasourceStateDescriptor = new MapStateDescriptor("mediasource_list_state", String.class, Media.class);

    private MapStateDescriptor<String, MediaCampaign> mediaCampaignStateDescriptor = new MapStateDescriptor("media_campaign_list_state", String.class, MediaCampaign.class);

    private MapStateDescriptor<String, AdMapping> adMappingMapStateDescriptor = new MapStateDescriptor("ad_mapping_list_state", String.class, AdMapping.class);

    private AppConfig appConfig;

    private JdbiContext jdbiContext;

    private GameMappingDao gameMappingDao;

    private MapState<String, Game> gameState;

    private MapState<String, Media> mediaSourceState;

    private MapState<String, MediaCampaign> mediaCampaignState;

    private MapState<String, AdMapping> adMappingMapState;

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

    @Override
    public void open(Configuration parameters) throws Exception {
        super.open(parameters);
        jdbiContext = DatabaseUtils.getCHGenJdbiClient(appConfig.getDbHost(), appConfig.getDbUser(), appConfig.getDbPassword());
        gameMappingDao = jdbiContext.getJdbi().onDemand(GameMappingDao.class);

        gameState = getRuntimeContext().getMapState(stateDescriptor);
        mediaSourceState = getRuntimeContext().getMapState(mediasourceStateDescriptor);
        mediaCampaignState = getRuntimeContext().getMapState(mediaCampaignStateDescriptor);
        adMappingMapState = getRuntimeContext().getMapState(adMappingMapStateDescriptor);
    }

    @Override
    public void flatMap(AppsFlyerEvent value, Collector<ActivationMetrics> out) throws Exception {
        int platform_id = 1;
        if (PlatformEnum.IOS.getName().equals(value.getPlatform())) {
            platform_id = 2;
        }

        //更新game
        Game game = gameState.get(value.getGame_id() + value.getPlatform());
        if (game == null) {
            boolean gameByPrimary = gameMappingDao.findGameByPrimary(value, platform_id);
            if (!gameByPrimary) {
                gameMappingDao.saveGame(value, platform_id);
            }
            gameState.put(value.getGame_id() + value.getPlatform(), new Game(platform_id, value.getGame_id()));
        }

        //mediaSource更新
        String mediaSource = value.getMedia_source();
        if (!Constants.DEFAULT_FIELD_VALUE.equals(mediaSource)) {
            Media media = mediaSourceState.get(mediaSource);
            if (media == null) {
                Optional<Media> mediaByPrimary = gameMappingDao.findMediaByPrimary(value);
                if (!mediaByPrimary.isPresent()) {
                    gameMappingDao.saveMediaSource(value);
                } else {
                    mediaSourceState.put(mediaSource, mediaByPrimary.get());
                }
            }
        }

        //MediaCampaign更新
        MediaCampaign mediaCampaign = mediaCampaignState.get(value.getMedia_source() + value.getCampaign());
        if (null == mediaCampaign) {
            Media media = mediaSourceState.get(mediaSource);
            if (null != media) {
                if (!gameMappingDao.existsMediaCampaign(value)) {
                    gameMappingDao.saveMediaCampaign(value, media);
                    mediaCampaignState.put(value.getMedia_source() + value.getCampaign(), new MediaCampaign(value.getMedia_source(), value.getCampaign()));
                }
            }
        }

        //adMapping 更新
        AdMapping adMapping = adMappingMapState.get(value.getCampaign_id() + value.getAd_set_id() + value.getAd_id());
        if (null == adMapping) {
            Media media = mediaSourceState.get(mediaSource);
            if (null != media) {
                gameMappingDao.saveAdMapping(value, media);
                adMappingMapState.put(value.getCampaign_id() + value.getAd_set_id() + value.getAd_id(),new AdMapping(value.getCampaign_id(),value.getAd_set_id(),value.getAd_id()));
            }
        }


    }

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


}
