package com.sf.sdk.demo.ads;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.sf.sdk.SFPlatform;
import com.sf.sdk.ads.SFAd;
import com.sf.sdk.ads.SFAdError;
import com.sf.sdk.ads.SFAdManager;
import com.sf.sdk.ads.SFAdPlatform;
import com.sf.sdk.ads.SFAdReward;
import com.sf.sdk.ads.SFAdSize;
import com.sf.sdk.ads.SFAdWrapper;
import com.sf.sdk.ads.SFDebugGeography;
import com.sf.sdk.ads.SFNativeAdTemplate;
import com.sf.sdk.ads.SFWaterfallType;
import com.sf.sdk.data.SFAdMobAdSettings;
import com.sf.sdk.data.SFAdRequest;
import com.sf.sdk.data.SFAdSettings;
import com.sf.sdk.data.SFAdUnitsConfig;
import com.sf.sdk.data.SFConsentFlowSettings;
import com.sf.sdk.data.SFMaxAdSettings;
import com.sf.sdk.demo.BaseActivity;
import com.sf.sdk.demo.R;
import com.sf.sdk.listeners.SFAdInitializationListener;
import com.sf.sdk.listeners.SFAdListener;
import com.sf.sdk.listeners.SFAdRevenueListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MixedAdsActivity extends BaseActivity implements View.OnClickListener {

    private static final boolean adAutoLoad = true;

    private String userId;
    private String shouldShowWaterfall;
    private boolean shouldShowFullscreenAd;
    private FrameLayout adContainer;
    private final Map<Integer, String> sfWaterfalls = new HashMap<>();
    private final Map<String, SFAdWrapper> sfAdWrappers = new HashMap<>();

    @Override
    protected int getLayoutResId() {
        return R.layout.content_ads;
    }

    @Override
    protected void initViews() {
        userId = getIntent().getStringExtra(Intent.EXTRA_USER);

        adContainer = findViewById(R.id.ad_container);

        findViewById(R.id.button_show_cmp).setOnClickListener(this);
        findViewById(R.id.button_app_open_ad).setOnClickListener(this);
        findViewById(R.id.button_interstitial_ad).setOnClickListener(this);
        findViewById(R.id.button_rewarded_ad).setOnClickListener(this);
        findViewById(R.id.button_banner_ad).setOnClickListener(this);
        findViewById(R.id.button_native_ad).setOnClickListener(this);

        findViewById(R.id.button_banner_visible).setOnClickListener(new View.OnClickListener() {

            private boolean bannerVisible = true;

            @Override
            public void onClick(View v) {
                SFAdWrapper wrapper = sfAdWrappers.get(SFWaterfallType.BANNER);
                if (wrapper != null) {
                    bannerVisible = !bannerVisible;
                    wrapper.setBannerVisibility(bannerVisible);
                }
            }
        });

        initAdManager();
        initAdListeners();
    }

    private void initAdManager() {
        String advertisingId = SFPlatform.getInstance().getAdvertisingId();
        List<String> testDeviceAdvertisingIds = new ArrayList<>();
        if (!TextUtils.isEmpty(advertisingId)) {
            testDeviceAdvertisingIds.add(advertisingId);
        }
        SFAdSettings settings = new SFAdSettings.Builder()
                .setMaxAdSettings(
                        new SFMaxAdSettings.Builder()
                                .setMuted(false)                                    // 设置是否静音
                                .setVerboseLoggingEnabled(true)                     // 设置是否启用详细日志记录
                                .setMediationDebuggerEnabled(false)                 // 设置是否启用中介调试器
                                .setAdUnitsConfig(
                                        new SFAdUnitsConfig.Builder()
                                                .setAppOpenAdUnitIdGuaranteedHigh("8e4b4c12bcb5ab9c")
                                                .setAppOpenAdUnitIdGuaranteedLow("8e4b4c12bcb5ab9c")
                                                .setInterstitialAdUnitIdGuaranteedHigh("61119a82d0c9db16")
                                                .setInterstitialAdUnitIdGuaranteedLow("61119a82d0c9db16")
                                                .setRewardedAdUnitIdGuaranteedHigh("0eefe4861dfe4c5f")
                                                .setRewardedAdUnitIdGuaranteedLow("0eefe4861dfe4c5f")
                                                .setBannerAdUnitIdGuaranteed("68e60452fce05539")
                                                .setNativeAdUnitIdGuaranteed("3a4208fa283f24a5")
                                                .build()
                                )                                                   // 设置保底的广告单元配置(建议配置)
                                .build()
                )
                .setAdMobAdSettings(
                        new SFAdMobAdSettings.Builder()
                                .setMuted(false)                                    // 设置是否静音
                                .setVolume(1.0f)                                    // 设置音频音量
                                .setAdInspectorEnabled(false)                       // 设置是否启用广告检查器
                                .setAdUnitsConfig(
                                        new SFAdUnitsConfig.Builder()
                                                .setAppOpenAdUnitIdGuaranteedHigh("ca-app-pub-3940256099942544/9257395921")
                                                .setAppOpenAdUnitIdGuaranteedLow("ca-app-pub-3940256099942544/9257395921")
                                                .setInterstitialAdUnitIdGuaranteedHigh("ca-app-pub-3940256099942544/1033173712")
                                                .setInterstitialAdUnitIdGuaranteedLow("ca-app-pub-3940256099942544/1033173712")
                                                .setRewardedAdUnitIdGuaranteedHigh("ca-app-pub-3940256099942544/5224354917")
                                                .setRewardedAdUnitIdGuaranteedLow("ca-app-pub-3940256099942544/5224354917")
                                                .setBannerAdUnitIdGuaranteed("ca-app-pub-3940256099942544/6300978111")
                                                .setNativeAdUnitIdGuaranteed("ca-app-pub-3940256099942544/2247696110")
                                                .build()
                                )                                                   // 设置保底的广告单元配置(建议配置)
                                .build()
                )
                .setConsentFlowSettings(
                        new SFConsentFlowSettings.Builder()
                                .setEnabled(true)                                   // 启用CMP流程
                                .setDebugGeography(SFDebugGeography.GDPR)           // 仅用于调试，发布时请删除
                                .setWaitForGameTriggerShow(true)                    // 设置是否等待游戏触发显示(默认为false)
                                .build()
                )
                .setUserIdentifier(userId)
                .setTestDeviceAdvertisingIds(testDeviceAdvertisingIds)
                .build();
        SFAdManager.getInstance().setAdAutoLoad(adAutoLoad); // 设置广告自动加载
        // SFAdManager.getInstance().setTestAdPlatform(SFAdPlatform.MAX); // 设置测试的广告平台(仅用于调试，发布时请删除)
        SFAdManager.getInstance().initializeSdk(settings, new SFAdInitializationListener() {
            @Override
            public void onInitializationComplete(String platform) {
                Log.i("TAG", "AdManager initialization complete: " + platform);
            }
        });
    }

    private void initAdListeners() {
        SFAdManager.getInstance().setAdListener(new SFAdListener() {
            @Override
            public void onAdRequest(String adUnitId, String adFormat) {

            }

            @Override
            public void onAdLoaded(SFAd ad) {
                String waterfall = ad.getWaterfall();
                SFAdWrapper sfAdWrapper = sfAdWrappers.get(waterfall);
                if (shouldShowFullscreenAd && sfAdWrapper != null && TextUtils.equals(waterfall, shouldShowWaterfall)) {
                    shouldShowWaterfall = null;
                    shouldShowFullscreenAd = false;
                    sfAdWrapper.showAd(ad.getAdFormat());      // 显示全屏广告并设置广告展示位置(必接)
                }
            }

            @Override
            public void onAdLoadFailed(String adUnitId, String adFormat, SFAdError error) {
                showToast(error.getMessage());
            }

            @Override
            public void onAdDisplayed(SFAd ad) {
            }

            @Override
            public void onAdDisplayFailed(SFAd ad, SFAdError error) {
                showToast(error.getMessage());
            }

            @Override
            public void onAdClicked(SFAd ad) {
            }

            @Override
            public void onAdDismissed(SFAd ad) {
            }

            @Override
            public void onUserRewarded(SFAd ad, SFAdReward reward) {
                showToast("Rewarded ad was displayed and user should receive the reward");
            }

            @Override
            public void onAdExpanded(SFAd ad) {
            }

            @Override
            public void onAdCollapsed(SFAd ad) {
            }
        });
        SFAdManager.getInstance().setAdRevenueListener(new SFAdRevenueListener() {
            @Override
            public void onAdRevenuePaid(@NonNull SFAd ad) {
                // SDK内部已经添加了广告收入数据统计，请不要重复记录 ad_impression 事件
            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.button_show_cmp) {
            SFAdManager.getInstance().getCmpService().showConsentForm(this);
            return;
        }
        String waterfall = sfWaterfalls.get(id);
        SFAdWrapper wrapper = sfAdWrappers.get(waterfall);
        if (wrapper == null) {
            wrapper = createAdWrapper(id);
            if (wrapper == null) {
                return;
            }
            waterfall = wrapper.getWaterfall();
            sfWaterfalls.put(id, waterfall);
            sfAdWrappers.put(waterfall, wrapper);
        }
        final String placement = wrapper.getAdFormat();
        if (wrapper.isFullscreenAd()) {
            if (wrapper.isReady()) {            // 判断广告是否加载完成
                wrapper.showAd(placement);      // 显示全屏广告并设置广告展示位置(必接)
            } else {
                shouldShowWaterfall = wrapper.getWaterfall();
                shouldShowFullscreenAd = true;
                showToast("Ad is loading, please wait");
            }
        } else if (wrapper.isNativeAd() && wrapper.isReady()) {
            adContainer.removeAllViews();
            int layoutResId;
            String platform = wrapper.getPlatform();
            if (SFAdPlatform.ADMOB.equals(platform)) {
                layoutResId = R.layout.game_admob_native_ad;
            } else if (SFAdPlatform.MAX.equals(platform)) {
                layoutResId = R.layout.game_max_native_ad;
            } else {
                return;
            }
            SFNativeAdTemplate nativeAdTemplate = new SFNativeAdTemplate.Builder(adContainer, layoutResId)
                    .setIconImageViewId(R.id.native_ad_icon)                    // 广告图标
                    .setTitleTextViewId(R.id.native_ad_title)                   // 广告标题
                    .setBodyTextViewId(R.id.native_ad_body)                     // 广告内容(可选)
                    .setAdvertiserTextViewId(R.id.native_ad_secondary)          // 广告主(可选)
                    .setStarRatingViewId(R.id.native_ad_star_rating)            // 商店评分(可选)
                    .setCallToActionViewId(R.id.native_ad_call_to_action)       // 广告点击按钮
                    .setMediaContentViewId(R.id.native_ad_media_content)        // 广告媒体内容(可选)
                    .setOptionsContentViewId(R.id.native_ad_options)            // 隐私信息(MAX平台必须指定)
                    .setNativeAdCloseViewId(R.id.native_ad_close)               // 广告关闭按钮(可选，可以游戏自行处理)
                    .build();
            wrapper.showNativeAd(placement, nativeAdTemplate);
        }
        if (!adAutoLoad) {
            wrapper.loadAd();               // 加载广告(未开启自动加载时需要主动调用该方法)
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        for (SFAdWrapper sfAdWrapper : sfAdWrappers.values()) {
            sfAdWrapper.setBannerAutoRefresh(true); // 启动自动刷新
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        for (SFAdWrapper sfAdWrapper : sfAdWrappers.values()) {
            sfAdWrapper.setBannerAutoRefresh(false); // 关闭自动刷新
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        for (SFAdWrapper sfAdWrapper : sfAdWrappers.values()) {
            sfAdWrapper.destroy();      // 销毁广告(释放资源)
        }
        sfAdWrappers.clear();
    }

    private SFAdWrapper createAdWrapper(int id) {
        if (id == R.id.button_app_open_ad) {
            return SFAdManager.getInstance().createAppOpenAd();
        } else if (id == R.id.button_interstitial_ad) {
            return SFAdManager.getInstance().createInterstitialAd();
        } else if (id == R.id.button_rewarded_ad) {
            return SFAdManager.getInstance().createRewardedAd();
        } else if (id == R.id.button_banner_ad) {
            SFAdRequest request = new SFAdRequest.Builder(this)
                    .setAdSize(SFAdSize.BANNER)
                    .setAdContainer(adContainer)
                    .build();
            return SFAdManager.getInstance().createBannerAd(request);
        } else if (id == R.id.button_native_ad) {
            return SFAdManager.getInstance().createNativeAd();
        }
        return null;
    }

    private void showToast(String message) {
        if (!TextUtils.isEmpty(message)) {
            Toast.makeText(this, message, Toast.LENGTH_LONG).show();
        }
    }

}