package com.pokkt.plugin.common;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.widget.RelativeLayout;

import com.pokkt.PokktAds;
import com.pokkt.plugin.papreact.PokktNativeExtension;
import com.pokkt.sdk.banners.PokktBannerView;

import org.json.JSONObject;

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

    public interface IUIHelperFunction {
        void execute();
    }

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

    @SuppressLint({"MissingPermission"})
    public static void process(String operation, final String params, final Activity activity) {
        switch (operation) {
            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) {
                    PokktAds.Debugging.printStackTrace("",e);
                }
            case "setThirdPartyUserId":
                PokktAds.setThirdPartyUserId(params);
                break;
            case "setAdPlayerViewConfig":
                PokktAds.setAdPlayerViewConfig(Parsers.getAdViewConfigFromJSONString(params));
                break;
            case "setUserDetails":
                PokktAds.setUserDetails(Parsers.getUserDetailsFromJSONString(params));
                break;
            case "setCallbackExtraParams":
                PokktAds.setCallbackExtraParams(Parsers.getExtraParamsFromJSONString(params));
                break;
            case "cacheAd":
                PokktAds.cacheAd(params, adDelegate);
                break;
            case "showAd":
                loadAd(params, activity);
                break;
            case "destroyBanner":
                PokktBannerAdapter.destroyBanner(activity);
                break;
            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) {
                    PokktAds.Debugging.printStackTrace("",e);
                }
            case "InGameAd_updateIGAData":
                PokktAds.InGameAd.updateIGAData(params);
                break;
            case "Debugging_shouldDebug":
                PokktAds.Debugging.shouldDebug(activity, Boolean.parseBoolean(params));
                break;
            case "Debugging_exportLog":
                runOnUiHelper(new IUIHelperFunction() {
                    public void execute() {
                        PokktAds.Debugging.exportLog(activity);
                    }
                }, activity);

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

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

                break;
            case "Debugging_showLog":
                PokktAds.Debugging.log(params);
                break;
            case "setDataAccessConsent":
                PokktAds.setDataAccessConsent(Parsers.getConsentInfoFromJSONString(params));
        }
    }

    private static void loadAd(final String jsonString, final Activity activity) {
        runOnUiHelper(new IUIHelperFunction() {
            public void execute() {
                try {
                    PokktAds.Debugging.log("loadBannerRect method called");

                    JSONObject jsonObject = new JSONObject(jsonString);
                    String screenId = jsonObject.optString("screenId");
                    if (jsonObject.has("bannerPosition")) {
                        int bannerTypes = Integer.parseInt(jsonObject.optString("bannerPosition", ""));
                        if (PokktBannerAdapter.bannerContainer != null) {
                            PokktAds.destroyBanner(PokktBannerAdapter.bannerContainer);
                            PokktBannerAdapter.bannerContainer = null;
                        }
                        PokktBannerAdapter.bannerContainer = new PokktBannerView(activity);
                        activity.addContentView(PokktBannerAdapter.bannerContainer, PokktBannerAdapter.getLayoutParams(bannerTypes, activity));
                        PokktAds.showAd(screenId, PokktBannerAdapter.bannerAdDelegate, PokktBannerAdapter.bannerContainer);
                    } else if ((jsonObject.has("width")) || (jsonObject.has("height"))) {
                        int width = Integer.parseInt(jsonObject.optString("width"));
                        int height = Integer.parseInt(jsonObject.optString("height"));
                        if (PokktBannerAdapter.bannerContainer != null) {
                            PokktAds.destroyBanner(PokktBannerAdapter.bannerContainer);
                            PokktBannerAdapter.bannerContainer = null;
                        }
                        PokktBannerAdapter.bannerContainer = new PokktBannerView(activity);
                        PokktBannerAdapter.bannerContainer.setX(Float.parseFloat(jsonObject.optString("x")));
                        PokktBannerAdapter.bannerContainer.setY(Float.parseFloat(jsonObject.optString("y")));

                        activity.addContentView(PokktBannerAdapter.bannerContainer, new RelativeLayout.LayoutParams(width, height));
                        PokktAds.showAd(screenId, PokktBannerAdapter.bannerAdDelegate, PokktBannerAdapter.bannerContainer);
                    } else {
                        PokktAds.showAd(screenId, adDelegate, null);
                    }
                } catch (Exception e) {
                    PokktAds.Debugging.printStackTrace("",e);
                }
            }
        }, activity);
    }

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

    @SuppressLint({"MissingPermission"})
    public static boolean isAdCached(String screenId) {
        return PokktAds.isAdCached(screenId);
    }

    private static PokktAds.PokktAdDelegate adDelegate = new PokktAds.PokktAdDelegate() {
        public void adCachingResult(String screenId, boolean isSuccess, double reward, String errorMessage) {
            try {
                PokktAds.Debugging.log("[POKKT-JAVA]: adCachingResult: " + screenId + " " + errorMessage +" " + reward);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("SCREEN_ID", screenId);
                jsonObject.put("IS_SUCCESS", isSuccess);
                jsonObject.put("REWARD", reward);
                jsonObject.put("ERROR_MESSAGE", errorMessage);
                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.EVENT_AD_CACHING_RESULT, jsonObject.toString());
            } catch (Throwable e) {
                PokktAds.Debugging.printStackTrace("",e);
            }
        }

        public void adDisplayedResult(String screenId, boolean isSuccess, String errorMessage) {
            try {
                PokktAds.Debugging.log("[POKKT-JAVA]: adDisplayedResult: " + screenId + " " + errorMessage);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("SCREEN_ID", screenId);
                jsonObject.put("IS_SUCCESS", isSuccess);
                jsonObject.put("ERROR_MESSAGE", errorMessage);
                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.EVENT_AD_DISPLAYED_RESULT, jsonObject.toString());
            } catch (Throwable e) {
                PokktAds.Debugging.printStackTrace("",e);
            }
        }

        public void adClosed(String screenId, boolean isComplete) {
            try {
                PokktAds.Debugging.log("[POKKT-JAVA]: adClosed: " + screenId + " " + isComplete);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("SCREEN_ID", screenId);
                jsonObject.put("AD_COMPLETED", isComplete);
                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.EVENT_AD_CLOSED, jsonObject.toString());
            } catch (Throwable e) {
                PokktAds.Debugging.printStackTrace("",e);
            }
        }

        @Override
        public void adGratified(String screenId, double reward) {
            try {
                PokktAds.Debugging.log("[POKKT-JAVA]: adGratified: " + screenId  + " " + reward);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("SCREEN_ID", screenId);
                jsonObject.put("REWARD", reward);
                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.EVENT_AD_GRATIFIED, jsonObject.toString());
            } catch (Throwable e) {
                PokktAds.Debugging.printStackTrace("",e);
            }
        }

        public void adClicked(String screenId) {
            try {
                PokktAds.Debugging.log("[POKKT-JAVA]: adClicked: " + screenId);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("SCREEN_ID", screenId);
                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.EVENT_AD_CLICKED, jsonObject.toString());
            } catch (Throwable e) {
                PokktAds.Debugging.printStackTrace("",e);
            }
        }
    };

    private static void initDelegates() {
        PokktAds.InGameAd.setDelegate(new PokktAds.InGameAd.IGADelegate() {
            public void igaAssetsReady(String screenId, String igaAssets) {
                PokktNativeExtension.notifyFramework(PokktToFrameworkEvents.IGA_ASSETS_READY, igaAssets);
            }

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