package com.gem.media;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.ads.cal.core.InitClean;
import com.ads.cal.core.ListenerHelper.AdListenerHelper;
import com.ads.cal.core.ListenerHelper.CleanReportInterface;
import com.ads.cal.core.ListenerHelper.SettingListenerHelper;
import com.ads.cal.core.data.JumpInfo;
import com.ads.cal.core.data.ReportInfo;
import com.ads.cal.picturetranslate.PictureApplication;
import com.ads.cal.picturetranslate.R;
import com.ads.cal.picturetranslate.activity.PictureTranslateResultActivity;
import com.ads.cal.picturetranslate.activity.PictureTranslateShowPhotoActivity;
import com.gem.media.ad.AdManager;
import com.gem.media.ad.AdmobInterstitialManager;
import com.gem.media.ad.AdmobNativeManager;
import com.gem.media.splash.base.protocol.Constants;
import com.gem.media.splash.base.utils.PkgUtils;
import com.google.android.gms.ads.VideoController;
import com.google.android.gms.ads.nativead.MediaView;
import com.google.android.gms.ads.nativead.NativeAd;
import com.google.android.gms.ads.nativead.NativeAdView;
import com.or.ange.dot.utils.LLog;

public class CleanUtil {

    public static void init(Application application) {
        InitClean.init(application, (context, jumpType, jumpInfo) -> {
            if (InitA.getInstance().isAppBackground()) {
                return;
            }
            Bundle bundle = new Bundle();
            String jumpTypeString = getJumpTypeString(jumpType);
            if (jumpType == JumpInfo.JUMP_ACTIVITY_CLEAN_SCAN || jumpType == JumpInfo.JUMP_ACTIVITY_PROCESS_SCAN) {
                PictureTranslateShowPhotoActivity.startPictureTranslateShowPhotoActivity(context, jumpInfo, jumpType);
                bundle.putString("jumpType", jumpTypeString);
            } else {
                if (jumpType == JumpInfo.JUMP_CLEAN_RESULT || jumpType == JumpInfo.JUMP_PROCESS_RESULT) {
                    loadChaPinAd();
                }
                startAudioDetailPageIfPossible(context, jumpInfo, jumpType);
                bundle.putString("jumpType", jumpTypeString);
            }
            try {
                Messenger messenger = InitA.getInstance().getCleanMessenger();
                if (messenger != null) {
                    Message message = Message.obtain();
                    message.what = 20003;
                    if (jumpInfo != null) {
                        bundle.putString("event", "cleanJump");
                        bundle.putString("pageName", jumpInfo.pageName);
                        String pkgName = PictureApplication.getApplication().getPackageName();
                        bundle.putString(Constants.MEDIA_PKG, pkgName);
                        bundle.putString(Constants.PARAM_VN, PkgUtils.getAppVersionName(PictureApplication.getApplication(), pkgName));
                        bundle.putString(Constants.PARAM_VC, PkgUtils.getAppVersionCode(PictureApplication.getApplication(), pkgName));
                    }
                    message.setData(bundle);
                    messenger.send(message);
                }
            } catch (Exception e) {
                LLog.e("AudioEditorInit", Log.getStackTraceString(e));
            }
        });
        try {
            setStopProcess();
        } catch (Exception e) {

        }
        try {
            setAdInterstitialDisplay();
        } catch (Exception e) {

        }
        try {
            setSettingHelper();
        } catch (Exception e) {

        }
        try {
            setAdNativeDisplay();
        } catch (Exception e) {

        }
        try {
            report();
        } catch (Exception e) {

        }
    }

    private static String getJumpTypeString(int jumpType) {
        switch (jumpType) {
            case JumpInfo.JUMP_ACTIVITY_CLEAN_SCAN:
                return "junk";
            case JumpInfo.JUMP_ACTIVITY_PROCESS_SCAN:
                return "process";
            case JumpInfo.JUMP_CLEAN_RESULT:
                return "junkResult";
            case JumpInfo.JUMP_PROCESS_RESULT:
                return "processResult";
            case JumpInfo.JUMP_CLEAN_SCAN_DETAILED:
                return "junkScanResult";
            case JumpInfo.JUMP_PROCESS_SCAN_DETAILED:
                return "processScanResult";
            default:
                return "unknown";
        }
    }

    private static void loadChaPinAd() {
        try {
            if (!AdmobInterstitialManager.instance().isAdAvailable()) {
                AdmobInterstitialManager.instance().loadAd(PictureApplication.getApplication(),
                        AdmobInterstitialManager.instance().loadIndex);
            }
        } catch (Exception e) {
            //
        }
    }


    private static void setStopProcess() {
        InitClean.INSTANCE.setStopProcessListener((s, stopProcessCallback) -> {
            try {
                Messenger messenger = InitA.getInstance().getCleanMessenger();
                LLog.e("AudioEditorInit", "pkg  "+s+"  messenger " + messenger);
                if (messenger != null) {
                    Message message = Message.obtain();
                    message.what = 20001;
                    messenger.send(message);
                }
            } catch (Exception e) {
                LLog.e("AudioEditorInit", Log.getStackTraceString(e));
            } finally {
                if (null != stopProcessCallback) {
                    stopProcessCallback.stopProcessSuccess();
                }
            }
        });
    }

    private static void setAdInterstitialDisplay() {
        InitClean.INSTANCE.setAdInterstitialDisplayListener(new AdListenerHelper.AdInterstitialDisplayListener() {
            @Override
            public void showAd(Context context, String scenario, AdListenerHelper.AdShownCallback adShownCallback) {
                InitA.getInstance().setAdShownCallback(adShownCallback);
                if (adShownCallback != null) {
                    if (AdmobInterstitialManager.instance().isAdAvailable()) {
                        if (context instanceof Activity) {
                            AdmobInterstitialManager.instance().showAd((Activity) context, scenario);
                        } else {
                            adShownCallback.onAdCompleted();
                        }
                    } else {
                        adShownCallback.onAdCompleted();
                    }
                }
            }

            @Override
            public void loadAd() {
                if (!AdmobInterstitialManager.instance().isAdAvailable()) {
                    AdmobInterstitialManager.instance().loadAd(PictureApplication.getApplication(),
                            AdmobInterstitialManager.instance().loadIndex);
                } else {
                    try {
                        Messenger messenger = InitA.getInstance().getCleanMessenger();
                        if (messenger != null) {
                            Message message = Message.obtain();
                            message.what = 20003;
                            Bundle bundle = new Bundle();
                            bundle.putString("event", "cl_AdCache");
                            String pkgName = PictureApplication.getApplication().getPackageName();
                            bundle.putString(Constants.MEDIA_PKG, pkgName);
                            bundle.putString(Constants.PARAM_VN, PkgUtils.getAppVersionName(PictureApplication.getApplication(), pkgName));
                            bundle.putString(Constants.PARAM_VC, PkgUtils.getAppVersionCode(PictureApplication.getApplication(), pkgName));
                            message.setData(bundle);
                            messenger.send(message);
                        }
                    } catch (Exception e) {
                        LLog.e("AudioEditorInit", Log.getStackTraceString(e));
                    }
                }
            }
        });
    }

    private static void setSettingHelper() {
        InitClean.INSTANCE.setSettingListenerHelper(new SettingListenerHelper() {
            @Override
            public void setCleanReminderStatus(int type, boolean b) {
                try {
                    Messenger messenger = InitA.getInstance().getCleanMessenger();
                    if (messenger != null) {
                        Message message = Message.obtain();
                        message.what = 20004;
                        Bundle bundle = new Bundle();
                        bundle.putInt("type", type);
                        bundle.putBoolean("value", b);
                        message.setData(bundle);
                        messenger.send(message);
                    }
                } catch (Exception e) {
                    LLog.e("AudioEditorInit", Log.getStackTraceString(e));
                }
            }
        });
    }

    private static void setAdNativeDisplay() {
        InitClean.INSTANCE.setAdNativeDisplayListener(new AdListenerHelper.AdNativeDisplayListener() {
            @Override
            public void showAd(Context context, String adPosition, String s1, AdListenerHelper.AdNativeShownCallback adNativeShownCallback) {
                LLog.e("AudioEditorInit", "setAdNativeDisplayListener   1");
                if (adNativeShownCallback != null) {
                    try {
                        InitA.getInstance().setAdNativeShownCallback(adNativeShownCallback);
                        LLog.e("AudioEditorInit", "setAdNativeDisplayListener   2");
                        AdmobNativeManager admobNativeManager = AdManager.getInstance().getAdmobNativeManager(adPosition);
                        if (admobNativeManager.isAdAvailable()) {
                            LLog.e("AudioEditorInit", "setAdNativeDisplayListener   4");
                            if (context instanceof Activity) {
                                NativeAdView view = (NativeAdView) LayoutInflater.from(context).inflate(R.layout.app_ad_unified, null);
                                LLog.e("AudioEditorInit", "setAdNativeDisplayListener   5 " + view);
                                populateNativeAdView(admobNativeManager, view);
                                adNativeShownCallback.onAdCompleted(view, admobNativeManager.getAdPosition());
                            } else {
                                adNativeShownCallback.onAdCompleted(null, admobNativeManager.getAdPosition());
                            }
                        } else {
                            adNativeShownCallback.onAdCompleted(null, admobNativeManager.getAdPosition());
                        }
                    } catch (Exception e) {
                        LLog.e("AudioEditorInit", "setAdNativeDisplayListener  " + Log.getStackTraceString(e));
                    }
                }
            }

            @Override
            public void loadAd(String adPosition) {
                AdmobNativeManager admobNativeManager = AdManager.getInstance().getAdmobNativeManager(adPosition);
                LLog.e("AudioEditorInit", "load native   1"+" cache "+admobNativeManager.isAdAvailable());

                if (!admobNativeManager.isAdAvailable()) {
                    admobNativeManager.loadAd(PictureApplication.getApplication(), admobNativeManager.loadIndex);
                }
            }
        });
    }

    private static void report() {
        InitClean.INSTANCE.setCleanReportInterfaceHelper(new CleanReportInterface() {
            @Override
            public void report(ReportInfo reportInfo) {
                if (null == reportInfo) {
                    return;
                }
                Bundle bundle = new Bundle();
                try {
                    String event = reportInfo.event;
                    if (!TextUtils.isEmpty(event)) {
                        bundle.putString("event", reportInfo.event);
                    }
                    String pageName= reportInfo.pageName;
                    if (!TextUtils.isEmpty(pageName)) {
                        bundle.putString("pageName", pageName);
                    }
                    String rate = reportInfo.rate;
                    if (!TextUtils.isEmpty(rate)) {
                        bundle.putString("rate", rate);
                    }
                    String cleanType = reportInfo.cleanType;
                    if (!TextUtils.isEmpty(cleanType)) {
                        bundle.putString("cleanType", cleanType);
                    }
                    String pkgName = PictureApplication.getApplication().getPackageName();
                    bundle.putString(Constants.MEDIA_PKG, pkgName);
                    bundle.putString(Constants.PARAM_VN, PkgUtils.getAppVersionName(PictureApplication.getApplication(), pkgName));
                    bundle.putString(Constants.PARAM_VC, PkgUtils.getAppVersionCode(PictureApplication.getApplication(), pkgName));

                } catch (Exception e) {
                    //
                }
                try {
                    Messenger messenger = InitA.getInstance().getCleanMessenger();
                    if (messenger != null) {
                        Message message = Message.obtain();
                        message.what = 20003;
                        message.setData(bundle);
                        messenger.send(message);
                    }
                } catch (Exception e) {
                    LLog.e("AudioEditorInit", Log.getStackTraceString(e));
                }
            }
        });
    }

    private static void startAudioDetailPageIfPossible(Context context, JumpInfo jumpInfo, int jumpType) {
        if (context instanceof Activity) {
            PictureTranslateResultActivity.start((Activity) context, jumpInfo, jumpType);
        }
    }

    public static void populateNativeAdView(AdmobNativeManager  manager, NativeAdView adView) {
        NativeAd nativeAd = manager.mNativeAd;
        // Set the media view.
        adView.setMediaView((MediaView) adView.findViewById(R.id.ad_media));

        // Set other ad assets.
        adView.setHeadlineView(adView.findViewById(R.id.ad_headline));
        adView.setBodyView(adView.findViewById(R.id.ad_body));
        adView.setCallToActionView(adView.findViewById(R.id.ad_call_to_action));
        adView.setIconView(adView.findViewById(R.id.ad_app_icon));
        adView.setPriceView(adView.findViewById(R.id.ad_price));
        adView.setStarRatingView(adView.findViewById(R.id.ad_stars));
        adView.setStoreView(adView.findViewById(R.id.ad_store));
        adView.setAdvertiserView(adView.findViewById(R.id.ad_advertiser));

        // The headline and mediaContent are guaranteed to be in every NativeAd.
        ((TextView) adView.getHeadlineView()).setText(nativeAd.getHeadline());
        adView.getMediaView().setMediaContent(nativeAd.getMediaContent());

        // These assets aren't guaranteed to be in every NativeAd, so it's important to
        // check before trying to display them.
        if (nativeAd.getBody() == null) {
            adView.getBodyView().setVisibility(View.INVISIBLE);
        } else {
            adView.getBodyView().setVisibility(View.VISIBLE);
            ((TextView) adView.getBodyView()).setText(nativeAd.getBody());
        }

        if (nativeAd.getCallToAction() == null) {
            adView.getCallToActionView().setVisibility(View.INVISIBLE);
        } else {
            adView.getCallToActionView().setVisibility(View.VISIBLE);
            ((Button) adView.getCallToActionView()).setText(nativeAd.getCallToAction());
        }

        if (nativeAd.getIcon() == null) {
            adView.getIconView().setVisibility(View.GONE);
        } else {
            ((ImageView) adView.getIconView()).setImageDrawable(nativeAd.getIcon().getDrawable());
            adView.getIconView().setVisibility(View.VISIBLE);
        }

        if (nativeAd.getPrice() == null) {
            adView.getPriceView().setVisibility(View.INVISIBLE);
        } else {
            adView.getPriceView().setVisibility(View.VISIBLE);
            ((TextView) adView.getPriceView()).setText(nativeAd.getPrice());
        }

        if (nativeAd.getStore() == null) {
            adView.getStoreView().setVisibility(View.INVISIBLE);
        } else {
            adView.getStoreView().setVisibility(View.VISIBLE);
            ((TextView) adView.getStoreView()).setText(nativeAd.getStore());
        }

        if (nativeAd.getStarRating() == null) {
            adView.getStarRatingView().setVisibility(View.INVISIBLE);
        } else {
            ((RatingBar) adView.getStarRatingView()).setRating(nativeAd.getStarRating().floatValue());
            adView.getStarRatingView().setVisibility(View.VISIBLE);
        }

        if (nativeAd.getAdvertiser() == null) {
            adView.getAdvertiserView().setVisibility(View.INVISIBLE);
        } else {
            ((TextView) adView.getAdvertiserView()).setText(nativeAd.getAdvertiser());
            adView.getAdvertiserView().setVisibility(View.VISIBLE);
        }

        // This method tells the Google Mobile Ads SDK that you have finished populating your
        // native ad view with this native ad.
        adView.setNativeAd(nativeAd);

        // Get the video controller for the ad. One will always be provided, even if the ad doesn't
        // have a video asset.
        VideoController vc = nativeAd.getMediaContent().getVideoController();

        // Updates the UI to say whether or not this ad has a video asset.
        if (nativeAd.getMediaContent() != null && nativeAd.getMediaContent().hasVideoContent()) {

            // Create a new VideoLifecycleCallbacks object and pass it to the VideoController. The
            // VideoController will call methods on this object when events occur in the video
            // lifecycle.
            vc.setVideoLifecycleCallbacks(
                    new VideoController.VideoLifecycleCallbacks() {
                        @Override
                        public void onVideoEnd() {
                            // Publishers should allow native ads to complete video playback before
                            // refreshing or replacing them with another ad in the same UI location.
                            super.onVideoEnd();
                        }
                    });
        }
    }
}
