package com.pokkt.papreact.common;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;

import com.pokkt.PokktAds;
import com.pokkt.papreact.PokktNativeExtension;
import com.pokkt.sdk.debugging.Logger;

import org.json.JSONObject;

import java.util.AbstractMap;
import java.util.Map;


public final class PokktAdsAdapter {
    static {
        initDelegates();
    }
    // PRAGMA -- Run On UI Thread Helper

    public interface IUIHelperFunction {
        void execute();
    }

    public static void runOnUiHelper(final IUIHelperFunction func, final Activity activity) {
        if (activity != null) {
            activity.runOnUiThread(new Runnable() {
                public void run() {
                    func.execute();
                }
            });
        } else {
            Logger.e("activity not found!");
        }
    }

    @SuppressLint("MissingPermission")
    public static void process(String operation, final String params, final Activity activity) {
        switch (operation) {
            // Common APIs
            case "setPokktConfig":
                try {
                    JSONObject jsonObject = new JSONObject(params);
                    String appId = jsonObject.optString("appId", "");
                    String securityKey = jsonObject.optString("securityKey", "");
                    PokktAds.setPokktConfig(appId, securityKey, activity);
                } catch (Exception e) {
                    Logger.printStackTrace(e);
                }

            case "setThirdPartyUserId":
                PokktAds.setThirdPartyUserId(params);
                break;

            case "setAdViewConfig":
                PokktAds.setAdPlayerViewConfig(Parsers.getAdViewConfigFromJSONString(params));
                break;

            case "setUserDetails":
                PokktAds.setUserDetails(Parsers.getUserDetailsFromJSONString(params));
                break;

            case "setCallbackExtraParams":
                PokktAds.setCallbackExtraParams(Parsers.getExtraParamsFromJSONString(params));
                break;


            // Video Ads APIs

            case "VideoAd_cacheRewarded":
                PokktAds.VideoAd.cacheRewarded(params);
                break;

            case "VideoAd_cacheNonRewarded":
                PokktAds.VideoAd.cacheNonRewarded(params);
                break;

            case "VideoAd_showRewarded":
                PokktAds.VideoAd.showRewarded(params);
                break;

            case "VideoAd_showNonRewarded":
                PokktAds.VideoAd.showNonRewarded(params);
                break;


            // Interstitial APIs

            case "Interstitial_cacheRewarded":
                PokktAds.Interstitial.cacheRewarded(params);
                break;

            case "Interstitial_cacheNonRewarded":
                PokktAds.Interstitial.cacheNonRewarded(params);
                break;

            case "Interstitial_showRewarded":
                PokktAds.Interstitial.showRewarded(params);
                break;

            case "Interstitial_showNonRewarded":
                PokktAds.Interstitial.showNonRewarded(params);
                break;


            // Banner Ads APIs

            case "Banner_loadBanner":
                PokktBannerAdapter.loadBanner(params, activity);
                break;

            case "Banner_loadBannerWithRect":
                PokktBannerAdapter.loadBannerWithRect(params, activity);
                break;

            case "Banner_destroyBanner":
                PokktBannerAdapter.destroyBanner(activity);
                break;


            // IGA APIs

            case "InGameAd_fetchAssets":
                PokktAds.InGameAd.fetchAssets(params);
                break;

            case "InGameAd_trackFUClick":
                try {
                    JSONObject jsonObject = new JSONObject(params);
                    int clickType = jsonObject.optInt("clickType");
                    String assetType = jsonObject.optString("assetType");
                    PokktAds.InGameAd.trackFUClick(clickType, assetType);
                } catch (Exception e) {
                    Logger.printStackTrace(e);
                }
                break;

            case "InGameAd_updateIGAData":
                PokktAds.InGameAd.updateIGAData(params);
                break;


            // Analytics APIs

            case "Analytics_setAnalyticsDetails":
                PokktAds.Analytics.setAnalyticsDetails(Parsers.getAnalyticsDetailsFromJSONString(params));
                break;

            case "Analytics_trackIAP":
                PokktAds.Analytics.trackIAP(Parsers.getIAPDetailsFromJSONString(params));
                break;


            // Debugging APIs

            case "Debugging_shouldDebug":
                PokktAds.Debugging.shouldDebug(activity, Boolean.parseBoolean(params));
                break;

            case "Debugging_exportLog":
                runOnUiHelper(new IUIHelperFunction() {
                    @Override
                    public void execute() {
                        PokktAds.Debugging.exportLog(activity);
                    }
                }, activity);
                break;

            case "Debugging_exportLogToCloud":
                runOnUiHelper(new IUIHelperFunction() {
                    @Override
                    public void execute() {
                        PokktAds.Debugging.exportLogToCloud(activity);
                    }
                }, activity);
                break;

            case "Debugging_showToast":
                runOnUiHelper(new IUIHelperFunction() {
                    @Override
                    public void execute() {
                        PokktAds.Debugging.showToast(activity, params);
                    }
                }, activity);
                break;

            case "Debugging_showLog":
                PokktAds.Debugging.showLog(params);
                break;


            // Consent Data

            case "setDataAccessConsent":
                PokktAds.setDataAccessConsent(Parsers.getConsentInfoFromJSONString(params));
                break;

        }
    }

    public static String getSDKVersion() {
        return PokktAds.getSDKVersion();
    }

    /*
     * @parm screenName = screenName
     * @param isRewarded = true / false
     * @return is add already cached or not.
     */
    @SuppressLint("MissingPermission")
    public static boolean isVideoAdCached(String screenName, boolean isRewarded) {
        return PokktAds.VideoAd.isAdCached(screenName, isRewarded);
    }

    /*
     * @parm screenName = screenName
     * @param isRewarded = true / false
     * @return is add already cached or not.
     */
    @SuppressLint("MissingPermission")
    public static boolean isInterstitialCached(String screenName, boolean isRewarded) {
        return PokktAds.Interstitial.isAdCached(screenName, isRewarded);
    }

    private static void initDelegates() {
        PokktAds.VideoAd.setDelegate(new PokktAds.VideoAd.VideoAdDelegate() {
            @Override @TargetApi(Build.VERSION_CODES.GINGERBREAD)
            public void videoAdCachingCompleted(String screenName, boolean isRewarded, double reward) {
                Map.Entry<String, String> entry = new AbstractMap.SimpleEntry<String, String>("REWARD", reward + "");

                String params = Parsers.getReturnParamsFromValues(screenName, isRewarded, entry);

                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.EVENT_VIDEO_AD_CACHING_COMPLETED, params);
            }

            @Override @TargetApi(Build.VERSION_CODES.GINGERBREAD)
            public void videoAdCachingFailed(String screenName, boolean isRewarded, String errorMessage) {
                Map.Entry<String, String> entry = new AbstractMap.SimpleEntry<String, String>("ERROR_MESSAGE", errorMessage);

                String params = Parsers.getReturnParamsFromValues(screenName, isRewarded, entry);

                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.EVENT_VIDEO_AD_CACHING_FAILED, params);
            }

            @Override
            public void videoAdDisplayed(String screenName, boolean isRewarded) {
                String params = Parsers.getReturnParamsFromValues(screenName, isRewarded);

                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.EVENT_VIDEO_AD_DISPLAYED, params);
            }

            @Override @TargetApi(Build.VERSION_CODES.GINGERBREAD)
            public void videoAdFailedToShow(String screenName, boolean isRewarded, String errorMessage) {
                Map.Entry<String, String> entry = new AbstractMap.SimpleEntry<String, String>("ERROR_MESSAGE", errorMessage);

                String params = Parsers.getReturnParamsFromValues(screenName, isRewarded, entry);

                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.EVENT_VIDEO_AD_FAILED_TO_SHOW, params);
            }

            @Override
            public void videoAdClosed(String screenName, boolean isRewarded) {
                //Map.Entry<String, String> entry = new AbstractMap.SimpleEntry<>("BACK_BUTTON", backButton + "");

                String params = Parsers.getReturnParamsFromValues(screenName, isRewarded);

                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.EVENT_VIDEO_AD_CLOSED, params);
            }

            @Override
            public void videoAdSkipped(String screenName, boolean isRewarded) {
                String params = Parsers.getReturnParamsFromValues(screenName, isRewarded);

                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.EVENT_VIDEO_AD_SKIPPED, params);
            }

            @Override
            public void videoAdCompleted(String screenName, boolean isRewarded) {
                String params = Parsers.getReturnParamsFromValues(screenName, isRewarded);

                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.EVENT_VIDEO_AD_COMPLETED, params);
            }

            @Override @TargetApi(Build.VERSION_CODES.GINGERBREAD)
            public void videoAdGratified(String screenName, boolean isRewarded, double reward) {
                Map.Entry<String, String> entry = new AbstractMap.SimpleEntry<String, String>("REWARD", reward + "");

                String params = Parsers.getReturnParamsFromValues(screenName, isRewarded, entry);

                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.EVENT_VIDEO_AD_GRATIFIED, params);
            }
        });

        PokktAds.Interstitial.setDelegate(new PokktAds.Interstitial.InterstitialDelegate() {
            @Override @TargetApi(Build.VERSION_CODES.GINGERBREAD)
            public void interstitialCachingCompleted(String screenName, boolean isRewarded, double reward) {
                Map.Entry<String, String> entry = new AbstractMap.SimpleEntry<String, String>("REWARD", reward + "");

                String params = Parsers.getReturnParamsFromValues(screenName, isRewarded, entry);

                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.EVENT_INTERSTITIAL_CACHING_COMPLETED, params);
            }

            @Override @TargetApi(Build.VERSION_CODES.GINGERBREAD)
            public void interstitialCachingFailed(String screenName, boolean isRewarded, String errorMessage) {
                Map.Entry<String, String> entry = new AbstractMap.SimpleEntry<String, String>("ERROR_MESSAGE", errorMessage);

                String params = Parsers.getReturnParamsFromValues(screenName, isRewarded, entry);

                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.EVENT_INTERSTITIAL_CACHING_FAILED, params);
            }

            @Override
            public void interstitialDisplayed(String screenName, boolean isRewarded) {
                String params = Parsers.getReturnParamsFromValues(screenName, isRewarded);

                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.EVENT_INTERSTITIAL_DISPLAYED, params);
            }

            @Override @TargetApi(Build.VERSION_CODES.GINGERBREAD)
            public void interstitialFailedToShow(String screenName, boolean isRewarded, String errorMessage) {
                Map.Entry<String, String> entry = new AbstractMap.SimpleEntry<String, String>("ERROR_MESSAGE", errorMessage);

                String params = Parsers.getReturnParamsFromValues(screenName, isRewarded, entry);

                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.EVENT_INTERSTITIAL_FAILED_TO_SHOW, params);
            }

            @Override
            public void interstitialClosed(String screenName, boolean isRewarded) {
                //Map.Entry<String, String> entry = new AbstractMap.SimpleEntry<>("BACK_BUTTON", backButton + "");

                String params = Parsers.getReturnParamsFromValues(screenName, isRewarded);

                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.EVENT_INTERSTITIAL_CLOSED, params);
            }

            @Override
            public void interstitialSkipped(String screenName, boolean isRewarded) {
                String params = Parsers.getReturnParamsFromValues(screenName, isRewarded);

                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.EVENT_INTERSTITIAL_SKIPPED, params);
            }

            @Override
            public void interstitialCompleted(String screenName, boolean isRewarded) {
                String params = Parsers.getReturnParamsFromValues(screenName, isRewarded);

                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.EVENT_INTERSTITIAL_COMPLETED, params);
            }

            @Override @TargetApi(Build.VERSION_CODES.GINGERBREAD)
            public void interstitialGratified(String screenName, boolean isRewarded, double reward) {
                Map.Entry<String, String> entry = new AbstractMap.SimpleEntry<String, String>("REWARD", reward + "");

                String params = Parsers.getReturnParamsFromValues(screenName, isRewarded, entry);

                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.EVENT_INTERSTITIAL_GRATIFIED, params);
            }
        });

        PokktAds.Banner.setDelegate(new PokktAds.Banner.BannerAdDelegate() {
            @Override
            public void bannerLoaded(String screenName) {
                try {
                    Logger.d("[POKKT-JAVA]: onBannerLoaded: " + screenName);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("SCREEN_NAME", screenName);
                    PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.BANNER_LOADED, jsonObject.toString());
                } catch(Exception e) {
                    Logger.printStackTrace(e);
                }
            }

            @Override
            public void bannerLoadFailed(String screenName, String errorMessage) {
                try {
                    Logger.d("[POKKT-JAVA]: onBannerLoadFailed: " + screenName + " and message: " + errorMessage);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("SCREEN_NAME", screenName);
                    jsonObject.put("ERROR_MESSAGE", errorMessage);
                    PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.BANNER_LOAD_FAILED, jsonObject.toString());
                } catch(Exception e) {
                    Logger.printStackTrace(e);
                }
            }
        });

        PokktAds.InGameAd.setDelegate(new PokktAds.InGameAd.IGADelegate() {
            @Override
            public void igaAssetsReady(String screenName, String igaAssets) {
                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.IGA_ASSETS_READY, igaAssets);
            }

            @Override
            public void igaAssetsFailed(String screenName, String errorMessage) {
                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.IGA_ASSETS_FAILED, errorMessage);
            }
        });
    }
}
