/*
 * Copyright (C) 2014 Google, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.ads.mediation.sample.customevent;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Keep;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;


import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.formats.NativeAdOptions;
import com.google.android.gms.ads.mediation.Adapter;
import com.google.android.gms.ads.mediation.InitializationCompleteCallback;
import com.google.android.gms.ads.mediation.MediationAdLoadCallback;
import com.google.android.gms.ads.mediation.MediationAdRequest;
import com.google.android.gms.ads.mediation.MediationConfiguration;
import com.google.android.gms.ads.mediation.MediationRewardedAd;
import com.google.android.gms.ads.mediation.MediationRewardedAdCallback;
import com.google.android.gms.ads.mediation.MediationRewardedAdConfiguration;
import com.google.android.gms.ads.mediation.NativeMediationAdRequest;
import com.google.android.gms.ads.mediation.VersionInfo;
import com.google.android.gms.ads.mediation.customevent.CustomEventBanner;
import com.google.android.gms.ads.mediation.customevent.CustomEventBannerListener;
import com.google.android.gms.ads.mediation.customevent.CustomEventInterstitial;
import com.google.android.gms.ads.mediation.customevent.CustomEventInterstitialListener;
import com.google.android.gms.ads.mediation.customevent.CustomEventNative;
import com.google.android.gms.ads.mediation.customevent.CustomEventNativeListener;
import com.advg.loader.AdViewBannerManager;
import com.advg.loader.AdViewInstlManager;
import com.advg.loader.AdViewNativeManager;
import com.advg.loader.AdViewVideoManager;
import com.advg.loader.loaderInterface.AdViewBannerListener;
import com.advg.loader.loaderInterface.AdViewInstlListener;
import com.advg.loader.loaderInterface.AdViewNativeListener;
import com.advg.loader.loaderInterface.AdViewVideoListener;
import com.advg.utils.AdViewUtils;

import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * A custom event for the Sample ad network. Custom events allow publishers to write their own
 * mediation adapter.
 *
 * Since the custom event is not directly referenced by the Google Mobile Ads SDK and is instead
 * instantiated with reflection, it's possible that ProGuard might remove it. Use the {@link Keep}}
 * annotation to make sure that the adapter is not removed when minifying the project.
 */
@Keep
public class AdVGCustomEvent extends Adapter implements CustomEventBanner,
        CustomEventInterstitial,
        CustomEventNative,
        MediationRewardedAd //reward ads used
{

    protected static final String TAG = AdVGCustomEvent.class.getSimpleName();
    private AdViewBannerManager adViewBIDView = null;
    private AdViewInstlManager adInstlBIDView = null;
    private AdViewNativeManager adViewNative = null;
    private AdViewVideoManager videoManager = null;
    private AdViewVideoListener adViewVideoListener = null;

    private AdViewNativeListener advListener;
    protected CustomEventBannerListener customEventBannerListener = null;
    protected CustomEventInterstitialListener  customEventInstListener = null;
    protected CustomEventNativeListener custEventNativeListener = null;
    /**
     * Used to forward rewarded video ad events to the Google Mobile Ads SDK.
     */
    private MediationRewardedAdCallback rewardedAdCallback;
    /**
     * A {@link MediationAdLoadCallback} that handles any callback when a Sample rewarded ad finishes
     * loading.
     */
    private MediationAdLoadCallback<MediationRewardedAd, MediationRewardedAdCallback> medAdLoadCallBack;

    protected Context mContextNative = null;
    protected Context mContextInstl = null;
    protected  boolean shouldReturnUrlsForImageAssets = false;
    private static SampleNativeAd native_ad;
    private static String native_adid = "";

    private static String imgURL = "";
    private static String iconURL = "";
    /**
     * Example of an extra field that publishers can use for a Native ad. In this example, the
     * String is added to a {@link Bundle} in {@link SampleUnifiedNativeAdMapper}.
     */
    public static final String DEGREE_OF_AWESOMENESS = "DegreeOfAwesomeness";
    /**
     * The pixel-to-dpi scale for images downloaded from the sample SDK's URL values. Scale value
     * is set in {@link SampleNativeMappedImage}.
     */
    public static final double SAMPLE_SDK_IMAGE_SCALE = 1.0;


    private static String video_appid = "";
    private static String video_posid = "";
    /**
     * The event is being destroyed. Perform any necessary cleanup here.
     */
    @Override
    public void onDestroy() {
    }

    /**
     * The app is being paused. This call will only be forwarded to the adapter if the developer
     * notifies mediation that the app is being paused.
     */
    @Override
    public void onPause() {
        // The sample ad network doesn't have an onPause method, so it does nothing.
    }

    /**
     * The app is being resumed. This call will only be forwarded to the adapter if the developer
     * notifies mediation that the app is being resumed.
     */
    @Override
    public void onResume() {
        // The sample ad network doesn't have an onResume method, so it does nothing.
    }

    @Override
    public void requestBannerAd(final Context context,
                                CustomEventBannerListener listener,
                                String serverParameter,
                                AdSize size,
                                MediationAdRequest mediationAdRequest,
                                Bundle customEventExtras) {
        /*
         * In this method, you should:
         *
         * 1. Create your banner view.
         * 2. Set your ad network's listener.
         * 3. Make an ad request.
         *
         * When setting your ad network's listener, don't forget to send the following callbacks:
         *
         * listener.onAdLoaded(this);
         * listener.onAdFailedToLoad(this, AdRequest.ERROR_CODE_*);
         * listener.onAdClicked(this);
         * listener.onAdOpened(this);
         * listener.onAdLeftApplication(this);
         * listener.onAdClosed(this);
         */
        customEventBannerListener = listener;
        int adSize = AdViewBannerManager.BANNER_SMART;
        int width = size.getWidth();
        int height = size.getHeight();
//        if (size.equals(AdSize.BANNER)) {
//            //320 x 50
//            adSize = AdViewBannerManager.BANNER_AUTO_FILL;
//            //adSize = 0;
//        }else if (size.equals(AdSize.MEDIUM_RECTANGLE)) {
//            //300 x 250
//            adSize = AdViewBannerManager.BANNER_MREC;
//        }


        if (width == AdSize.BANNER.getWidth() && height == AdSize.BANNER.getHeight()) {
            //if (widthInPixels == 320 && heightInPixels == 50) {
            adSize = AdViewBannerManager.BANNER_SMART;
        }else if (width == AdSize.MEDIUM_RECTANGLE.getWidth() && height == AdSize.MEDIUM_RECTANGLE.getHeight()) {
            adSize = AdViewBannerManager.BANNER_MREC;
        }

        String para[] = serverParameter.split("\\;");
        String appid = "",posid = "";
        appid = para[0];
        if (para.length > 1) {
            posid = para[1];
        }
        //////////////////////adview banner manager ////////////////////////////
        adViewBIDView = new AdViewBannerManager(
                context,
                appid,
                posid,    //test_mrec_Video_POSID
                adSize,
                true);

        adViewBIDView.setOnAdViewListener(new AdViewBannerListener() {
            @Override
            public void onAdReady() {

            }
            @Override
            public void onAdClicked() {
                if (null != customEventBannerListener) {
                    customEventBannerListener.onAdClicked();
                    customEventBannerListener.onAdOpened();
                    // Only call onAdLeftApplication if your ad network actually exits the developer's app.
                    customEventBannerListener.onAdLeftApplication();
                }
            }

            @Override
            public void onAdDisplayed() {

            }
            @Override
            public void onAdReceived() {
                if (null != customEventBannerListener) {
                    customEventBannerListener.onAdLoaded(adViewBIDView.getAdViewLayout());

//                    if (context instanceof Activity) {
//                        ((Activity)context).runOnUiThread(new Runnable() { //wilder 2020 for non-activity
//                            @Override
//                            public void run() {
//                                Log.i(TAG, "!!!!! [admob-adview-banner] onAdReceived !!!!");
//                                customEventBannerListener.onAdLoaded(adViewBIDView.getAdViewLayout());
//                            }
//                        });
//                    }
                }
            }

            @Override
            public void onAdFailedReceived(String s) {
                if (null != customEventBannerListener)
                    customEventBannerListener.onAdFailedToLoad(AdRequest.ERROR_CODE_INTERNAL_ERROR);
            }

            @Override
            public void onAdClosed() {
                if (null != customEventBannerListener)
                    customEventBannerListener.onAdClosed();
            }

        });

        //adViewBIDView.setGDPR2(1,Gdpr);
        adViewBIDView.setRefreshTime(-1);
        //adViewBIDView.setTestMode(true);

    }


    @Override
    public void requestInterstitialAd(Context context,
                                      CustomEventInterstitialListener listener,
                                      String serverParameter,
                                      MediationAdRequest mediationAdRequest,
                                      Bundle customEventExtras) {
        /*
         * In this method, you should:
         *
         * 1. Create your interstitial ad.
         * 2. Set your ad network's listener.
         * 3. Make an ad request.
         *
         * When setting your ad network's listener, don't forget to send the following callbacks:
         *
         * listener.onAdLoaded(this);
         * listener.onAdFailedToLoad(this, AdRequest.ERROR_CODE_*);
         * listener.onAdOpened(this);
         * listener.onAdLeftApplication(this);
         * listener.onAdClosed(this);
         */
        customEventInstListener = listener;
        mContextInstl = context;
        String para[] = serverParameter.split("\\;");
        String appid = "",posid = "";
        appid = para[0].trim();
        if (para.length > 1) {
            posid = para[1].trim();
        }

        adInstlBIDView = new AdViewInstlManager(context,
                appid,
                posid,
                true //有关闭按钮：true，无关闭按钮：false
                );

        adInstlBIDView.setOnAdViewListener(new AdViewInstlListener() {
            @Override
            public void onAdReady() {

                Log.i("==AdInstlActivity==", "====onAdReady==");

            }
            @Override
            public void onAdClicked() {
                if (null != customEventInstListener) {
                    customEventInstListener.onAdClicked();
                    customEventInstListener.onAdOpened();
                    // Only call onAdLeftApplication if your ad network actually exits the developer's app.
                    customEventInstListener.onAdLeftApplication();

                }
            }

            @Override
            public void onAdDisplayed() {

            }
            @Override
            public void onAdReceived() {
                Log.i("==AdInstlActivity==", "====onAdReceived==");
                if (null != customEventInstListener)
                    customEventInstListener.onAdLoaded();
            }

            @Override
            public void onAdFailedReceived(String s) {

                Log.i("==AdInstlActivity==", "====onAdFailedReceived==");
                if (null != customEventInstListener)
                    customEventInstListener.onAdFailedToLoad(AdRequest.ERROR_CODE_INTERNAL_ERROR);
            }

            @Override
            public void onAdClosed() {

                if (null != customEventInstListener)
                    customEventInstListener.onAdClosed();
            }

        });

    }

    @Override
    public void showInterstitial() {
        // Show your interstitial ad.
        Log.i("==AdInstlActivity==", "====showInterstitial()==");
        adInstlBIDView.showInstl(mContextInstl);
    }

    @Override
    public void loadRewardedAd( MediationRewardedAdConfiguration mediationRewardedAdConfiguration,
                                MediationAdLoadCallback<MediationRewardedAd, MediationRewardedAdCallback> mediationAdLoadCallback) {
        Log.i(TAG, "!!!!! [admob-adview] loadRewardedAd !!!!");
        //String serverParameter = mediationRewardedAdConfiguration.getServerParameters().getString("ad_unit");
        String serverParameter = mediationRewardedAdConfiguration.getServerParameters().getString("parameter");
        if (TextUtils.isEmpty(serverParameter)) {
            mediationAdLoadCallback.onFailure("!!!! server paramert is empty, pls check server settings !!!!");
            return;
        }
        String para[] = serverParameter.split("\\;");
        String appid = "",posid = "";
        appid = para[0];
        if (para.length > 1) {
            posid = para[1];
        }

        this.medAdLoadCallBack = mediationAdLoadCallback;

        adViewVideoListener = new com.advg.loader.loaderInterface.AdViewVideoListener() {
            @Override
            public void onFailedReceivedVideo(String error) {
                Log.i(TAG, "!!!!![admob-adview] onFailedRecievedVideo:"+error + "!!!!");
                medAdLoadCallBack.onFailure(error.toString());
            }
            @Override
            public void onVideoStartPlayed() {

                Log.i(TAG, "++++++++++++ [admob-adview]onVideoStartPlayed ++++++++++");
                rewardedAdCallback.onAdOpened();
                rewardedAdCallback.onVideoStart();
                rewardedAdCallback.reportAdImpression();
            }
            @Override
            public void onVideoFinished() {
                Log.i(TAG, "++++++++++++[admob-adview] onVideoFinished ++++++++++++");
                rewardedAdCallback.onVideoComplete();
            }
            @Override
            public void onVideoClosed() {
                Log.i(TAG, "++++++++++++[admob-adview] onVideoClosed ++++++++++++");
                rewardedAdCallback.onAdClosed();
            }
            @Override
            public void onPlayedError(String arg0) {
                Log.i(TAG, "!!!!![admob-adview] onPlayedError:"+arg0 + "!!!!!");
                medAdLoadCallBack.onFailure(arg0.toString());

            }
            @Override
            public void onReceivedVideo(String arg0) {

                Log.i(TAG, "++++ [admob-adview] onRecievedVideo:"+arg0 + "++++");

            }
            @Override
            public void onVideoReady() {
                Log.i(TAG, "++++ [admob-adview] onVideoReady +++");
                //videoManager.playVideo(this);
                rewardedAdCallback = medAdLoadCallBack.onSuccess(AdVGCustomEvent.this);

            }
            @Override
            public void onVideoClicked(int x, int y) {
                rewardedAdCallback.reportAdClicked();
            }
        };

        video_appid = appid;
        video_posid = posid;
        rewardedAdCallback = medAdLoadCallBack.onSuccess(AdVGCustomEvent.this);

        /*
        videoManager = new AdViewVideoManager(
                //this,
                mediationRewardedAdConfiguration.getContext(),
                appid,
                posid,
                adViewVideoListener,
                false);

        videoManager.setGDPR2(1,Gdpr);

        // 设置屏幕方向，取值可参照ActivityInfo.SCREEN_XXXXXX 定义的常量
        videoManager.setVideoOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        //videoManager.setAutoPlay(false);

         */

    }


    @Override
    public void showAd(Context context) {

        Log.i(TAG, "++++ [admob-adview] show reward ad ++++");

        if (!(context instanceof Activity)) {
            rewardedAdCallback.onAdFailedToShow(
                    "An activity context is required to show Sample rewarded ad.");
            return;
        }
        videoManager = new AdViewVideoManager(
                //this,
                context,
                video_appid,
                video_posid,
                adViewVideoListener,
                false);

        //videoManager.setGDPR2(1,Gdpr);
        // 设置屏幕方向，取值可参照ActivityInfo.SCREEN_XXXXXX 定义的常量
        videoManager.setVideoOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        //videoManager.setAutoPlay(false);

    }

    @Override
    public void requestNativeAd(Context context,
                                CustomEventNativeListener customEventNativeListener,
                                String serverParameter,
                                NativeMediationAdRequest nativeMediationAdRequest,
                                Bundle extras) {
        custEventNativeListener = customEventNativeListener;
        mContextNative = context;
        NativeAdOptions options = nativeMediationAdRequest.getNativeAdOptions();
        if (options != null) {
            shouldReturnUrlsForImageAssets = !options.shouldReturnUrlsForImageAssets();
        }
        String para[] = serverParameter.split("\\;");
        String appid = "",posid = "";
        appid = para[0];
        if (para.length > 1) {
            posid = para[1];
        }

        //////////////////
        advListener = new com.advg.loader.loaderInterface.AdViewNativeListener() {
            /**
             * 请求失败时调用该方法
             *
             * @param arg0
             *            失败信息
             *
             */
            @Override
            public void onNativeAdReceiveFailed(String arg0) {
                Log.i("AdNativeActivity", "onNativeAdReceiveFailed " + arg0);
                if (custEventNativeListener != null)
                    custEventNativeListener.onAdFailedToLoad(AdRequest.ERROR_CODE_INTERNAL_ERROR);
            }
            /**
             * 当请求成功时调用该方法
             *
             * @param nativeAdList
             *            类型为List<HashMap<String,Object>>，返回得字段内容如下：
             *            title--> 广告标题
             *            adImage-->大图url
             *            adIcon--> Icon图片链接
             *            adFlagLogo--> 广告logo
             *            desc--> 广告描述文字
             *            sec_description--> 广告描述文字2
             * 请着重关注 title,adImage,adIcon,desc 这四个字段
             */
            @Override
            public void onNativeAdReceived(List nativeAdList) {
                Log.i("AdNativeActivity", "onNativeAdReceived");
                native_ad = createSampleAppInstallAd(nativeAdList);
            }
            @Override
            public void onDownloadStatusChange(int arg0) {

            }
            @Override
            public void onNativeAdClosed(View view) {

            }
        };

        adViewNative = new AdViewNativeManager(context,
                appid,
                posid,
                advListener
        );
        ////////////////////
        if (!nativeMediationAdRequest.isUnifiedNativeAdRequested()) {
            Log.e(TAG, "Failed to load ad. Request must be for unified native ads.");
            custEventNativeListener.onAdFailedToLoad(AdRequest.ERROR_CODE_INVALID_REQUEST);
            return;
        }

        //adViewNative.setGDPR2(1, Gdpr);
        adViewNative.requestAd();

    }


    // This method won't be called for custom events.
    @Override
    public void initialize(Context context,
                           InitializationCompleteCallback initializationCompleteCallback,
                           List<MediationConfiguration> list) {

        AdViewUtils.logInfo("==== [adMOb] initialize ====");
        return;
    }

    @Override
    public VersionInfo getVersionInfo() {
        String versionString = "1.0.1"; //BuildConfig.VERSION_NAME;
        String[] splits = versionString.split("\\.");

        if (splits.length >= 4) {
            int major = Integer.parseInt(splits[0]);
            int minor = Integer.parseInt(splits[1]);
            int micro = Integer.parseInt(splits[2]) * 100 + Integer.parseInt(splits[3]);
            return new VersionInfo(major, minor, micro);
        }

        return new VersionInfo(0, 0, 0);
    }

    @Override
    public VersionInfo getSDKVersionInfo() {
        String versionString = "1.0.0";//SampleAdRequest.getSDKVersion();
        String[] splits = versionString.split("\\.");

        if (splits.length >= 3) {
            int major = Integer.parseInt(splits[0]);
            int minor = Integer.parseInt(splits[1]);
            int micro = Integer.parseInt(splits[2]);
            return new VersionInfo(major, minor, micro);
        }

        return new VersionInfo(0, 0, 0);
    }

    /* -----------------------------------------------------------------------------------------
    /////////////////////////////////////// aimed functions //////////////////////////////////////
        ---------------------------------------------------------------------------------------
     */
    private SampleNativeAd createSampleAppInstallAd(List nativeAdList) {
        SampleNativeAd nativeAdSimple = new SampleNativeAd();
        //////////////// start////////////

        for(int i = 0; i < nativeAdList.size(); i++) {
            //holder = new ViewHolder();
            final HashMap<String, Object> nativeAd = (HashMap) nativeAdList.get(i);
            //HashMap<String, Object> nativeAd = (HashMap) native_AdList.get(0); //wilder for test omsdk 0926
            //set item value
            nativeAdSimple.setHeadline("Adview Ads Mediation");
            if (!nativeAd.toString().contains("videoUrl")) {
                //得到可用的图片
                if (null != nativeAd.get("adImage")) {
                    imgURL = ((CharSequence) nativeAd.get("adImage")).toString();
                    nativeAdSimple.setImageUri(Uri.parse(imgURL));
                }
                if (null != nativeAd.get("adIcon")) {
                    iconURL = ((CharSequence) nativeAd.get("adIcon")).toString();
                    nativeAdSimple.setIconUri(Uri.parse(iconURL));
                }
                if (null != nativeAd.get("adFlagIcon")) {
                    String adicon_url = ((CharSequence) nativeAd.get("adFlagIcon")).toString();
                }
                if (null != nativeAd.get("adFlagLogo")) {
                    String adlogo_url = ((CharSequence) nativeAd.get("adFlagLogo")).toString();
                }
                if (null != nativeAd.get("description")) {
                    String str_desc = ((CharSequence) nativeAd.get("description")).toString();
                    nativeAdSimple.setBody(str_desc);
                }
                if (null != nativeAd.get("sec_description")) {
                    String str_desc2 = ((CharSequence) nativeAd.get("sec_description")).toString();
                }
                if (null != nativeAd.get("title")) {
                    String str_title = ((CharSequence) nativeAd.get("title")).toString();
                    nativeAdSimple.setHeadline(str_title);
                }

                if (null != nativeAd.get("adId")) {
                    native_adid = ((CharSequence)nativeAd.get("adId")).toString();
                }
                //privacy image
                if (null != nativeAd.get("privacy_image")) {
                    String url = ((CharSequence) nativeAd.get("privacy_image")).toString();
//                    String click_url = "";
//                    if (null != nativeAd.get("privacy_click")) {
//                        click_url = ((CharSequence) nativeAd.get("privacy_click")).toString();
//                    }
                    nativeAdSimple.setInformationIcon(createInformationIconImageView(url));
                    //holder.privacyImg = getHttpBitmap(url);

                }
            }else {
                String videoURL = ((CharSequence)nativeAd.get("videoUrl")).toString();
            }
            nativeAdSimple.setCallToAction("Take Action!");
            nativeAdSimple.setDegreeOfAwesomeness("Quite Awesome");
            nativeAdSimple.setPrice(1.99);
            nativeAdSimple.setStarRating(4.5);
            nativeAdSimple.setStoreName("Sample Store");

            // We pretend 80% of network's inventory has video assets and 20% doesn't.
            nativeAdSimple.setMediaView(null);
//            if ((new Random()).nextInt(100) < 80) {
//                nativeAdSimple.setMediaView(new SampleMediaView(mContextNative));
//            } else {
//                nativeAdSimple.setMediaView(null);
//            }
            // There are other options offered in the SampleNativeAdRequest,
            // but for simplicity's sake, this is the only one we'll put to use.
            if (shouldReturnUrlsForImageAssets) {
                new Thread(new Runnable(){
                    @Override
                    public void run() {
                        try {
                            if (iconURL.length() > 0) {
                                Drawable icon;
                                icon = loadImageFromNetwork(iconURL);
                                native_ad.setIcon(icon);
                            }
                            if (imgURL.length() > 0) {
                                Drawable img;
                                img = loadImageFromNetwork(imgURL);
                                native_ad.setImage(img);
                            }
                            Message message = new Message();
                            message.what = NATIVE_AD_RECEIVED;
                            updateHandler.sendMessage(message);

                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }).start();

            }
            //wilder 2021
            nativeAdSimple.setAdvg_adid(native_adid);
            nativeAdSimple.setAdvg_native(adViewNative);
        }
        

        return nativeAdSimple;
    }
    private final static int NATIVE_AD_RECEIVED = 99;
    private Handler updateHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            try {
                switch (msg.what) {
                    case NATIVE_AD_RECEIVED:

                        SampleUnifiedNativeAdMapper mapper = new SampleUnifiedNativeAdMapper(native_ad);
                        custEventNativeListener.onAdLoaded(mapper);

                        //customEventNativeListener.onAdImpression(); //这里发展示汇报
                        //adViewNative.omsdkNativeCreateSession(v2);
                        break;

                    default:
                        Log.i("Native:", "other events " );
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private Drawable loadImageFromNetwork(String urladdr) {
        Drawable drawable = null;
        HttpURLConnection conn;
        try{
            URL myFileURL = new URL(urladdr);
            if (urladdr.startsWith("https://")) {
                conn = (HttpsURLConnection) myFileURL.openConnection();
                ((HttpsURLConnection) conn).setHostnameVerifier(new BrowserCompatHostnameVerifier());
                //handleSSLHandshake((HttpsURLConnection)conn);

            } else {
                conn = (HttpURLConnection) myFileURL.openConnection();
            }

            //HttpURLConnection conn=(HttpURLConnection)myFileURL.openConnection();
            //设置超时时间为6000毫秒，conn.setConnectionTiem(0);表示没有时间限制
            conn.setConnectTimeout(6000);
            //连接设置获得数据流
            conn.setDoInput(true);
            //不使用缓存
            conn.setUseCaches(false);
            InputStream is = conn.getInputStream();

            drawable = Drawable.createFromStream(/*new URL(urladdr).openStream()*/is, /*"src"*/null);

        }catch(IOException e){
            Log.d("AdVGCustomEvent:",e.getMessage());
        }
        return drawable;


    }


    private ImageView createInformationIconImageView( String imgUrl ) {
        ImageView informationIconImageView = new ImageView(mContextNative);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        informationIconImageView.setLayoutParams(params);
        //informationIconImageView.setImageResource(com.google.ads.mediation.sample.sdk.R.drawable.ic_info_outline_black_24px);
        informationIconImageView.setImageURI(Uri.parse(imgUrl));

        informationIconImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null != adViewNative) {
                    adViewNative.showPrivacyInfo();
                }
            }
        });

        return informationIconImageView;
    }

}
