package com.applovin.mediation.adapters;

import static com.applovin.sdk.AppLovinSdkUtils.runOnUiThread;

import android.app.Activity;
import android.app.Application;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;


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.applovin.impl.sdk.utils.BundleUtils;
import com.applovin.mediation.MaxAdFormat;
import com.applovin.mediation.MaxReward;
import com.applovin.mediation.adapter.MaxAdViewAdapter;
import com.applovin.mediation.adapter.MaxAdapterError;
import com.applovin.mediation.adapter.MaxInterstitialAdapter;
import com.applovin.mediation.adapter.MaxRewardedAdapter;
import com.applovin.mediation.adapter.MaxSignalProvider;
import com.applovin.mediation.adapter.listeners.MaxAdViewAdapterListener;
import com.applovin.mediation.adapter.listeners.MaxInterstitialAdapterListener;
import com.applovin.mediation.adapter.listeners.MaxNativeAdAdapterListener;
import com.applovin.mediation.adapter.listeners.MaxRewardedAdapterListener;
import com.applovin.mediation.adapter.listeners.MaxSignalCollectionListener;
import com.applovin.mediation.adapter.parameters.MaxAdapterInitializationParameters;
import com.applovin.mediation.adapter.parameters.MaxAdapterParameters;
import com.applovin.mediation.adapter.parameters.MaxAdapterResponseParameters;
import com.applovin.mediation.adapter.parameters.MaxAdapterSignalCollectionParameters;
import com.applovin.mediation.nativeAds.MaxNativeAd;
import com.applovin.mediation.nativeAds.MaxNativeAdView;
import com.applovin.sdk.AppLovinSdk;
import com.applovin.sdk.AppLovinSdkConfiguration;
import com.applovin.sdk.AppLovinSdkUtils;

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

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.net.ssl.HttpsURLConnection;

/**
 * Created by Advg 2022
 */
public class AdVgMediationAdapter
        extends MediationAdapterBase
        implements MaxSignalProvider, MaxInterstitialAdapter, MaxRewardedAdapter, MaxAdViewAdapter
{
    private static final AtomicBoolean initialized = new AtomicBoolean();

    private static InitializationStatus status;

    protected static final String TAG = AdVgMediationAdapter.class.getSimpleName();

    private static String appId;

    private AdViewBannerManager adViewBIDView = null;
    private AdViewInstlManager adInstlBIDView = null;
    private AdViewNativeManager adViewNative = null;
    private AdViewVideoManager videoManager = null;
    private AdViewVideoListener adViewVideoListener = null;

    private AdViewNativeListener advListener;

    private boolean nativeAdFaild = false;

    private boolean testLine = true;
    public static String user_GDPR = "BOEFEAyOEFEAyAHABDENAI4AAAB9vABAASA";

    // Explicit default constructor declaration
    public AdVgMediationAdapter(final AppLovinSdk sdk) {
        super( sdk );
    }

    @Override
    public String getSdkVersion()
    {
        return "4.3.6";
    }

    @Override
    public String getAdapterVersion()
    {
        return "1.0";
    }

    @Override
    public void onDestroy()
    {
        if ( adInstlBIDView != null )
        {
            adInstlBIDView = null;

        }

    }

    @Override
    public void collectSignal(final MaxAdapterSignalCollectionParameters parameters, final Activity activity, final MaxSignalCollectionListener callback)
    {
        log( "Collecting signal for " + parameters.getAdFormat() + " ad..." );

    }

    @Override
    public void initialize(final MaxAdapterInitializationParameters parameters, final Activity activity, final OnCompletionListener onCompletionListener)
    {
        if ( initialized.compareAndSet( false, true ) )
        {
            status = InitializationStatus.INITIALIZING;

            appId = parameters.getServerParameters().getString( "app_id" );
            Log.i( "[AdvgAdpter-initialize]","Initializing AdVG SDK with app id: " + appId + "..." );

            final String[] zoneIds = getZoneIds( parameters );

            // NOTE: `activity` can only be null in 11.1.0+, and `getApplicationContext()` is introduced in 11.1.0
            Application application = ( activity != null ) ? activity.getApplication() : (Application) getApplicationContext();

            final boolean initialized = true;

            status = initialized ? InitializationStatus.INITIALIZED_SUCCESS : InitializationStatus.INITIALIZED_FAILURE;
        }

        onCompletionListener.onCompletion( status, null );
    }

    @Override
    public void loadAdViewAd(final MaxAdapterResponseParameters parameters, final MaxAdFormat adFormat,
                             final Activity activity, final MaxAdViewAdapterListener listener)
    {
        final String posId = parameters.getThirdPartyAdPlacementId();
        final String bidResponse = parameters.getBidResponse();

        Log.i( "==loadAdViewAd ==","Loading " + ( TextUtils.isEmpty( bidResponse ) ? "bidding " : "" ) + adFormat.getLabel()
                + " ad for zone id " + posId + "..." );

        if ( !isAdVgConfigured() )
        {
            Log.i( "==loadAdViewAd ==","AdVg SDK is not initialized" );

            listener.onAdViewAdLoadFailed( MaxAdapterError.NOT_INITIALIZED );
            return;
        }
        //get the options
        final Bundle serverParameters = parameters.getServerParameters();

        /////////////adview 's porting
        final int adSize = sizeFromAdFormat(adFormat);

        //////////////////////adview banner manager ////////////////////////////
        //============================================

                adViewBIDView = new AdViewBannerManager(
                        activity,
                        appId,
                        posId,    //test_mrec_Video_POSID
                        adSize,
                        true);

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

                        log( adFormat.getLabel() + " ad clicked" );
                        if (null != listener)
                            listener.onAdViewAdClicked();

                    }

                    @Override
                    public void onAdDisplayed() {
                        if (null != listener) {
                            listener.onAdViewAdDisplayed();
                        }
                    }
                    @Override
                    public void onAdReceived() {
                        //advg fix
                        Log.i( "==onAdReceived() ==",adFormat.getLabel() + " ad loaded" );
                        if (null != listener)
                            listener.onAdViewAdLoaded(adViewBIDView.getAdViewLayout());

                    }

                    @Override
                    public void onAdFailedReceived(String s) {

                        Log.i( "onAdFailedReceived()", adFormat.getLabel() + " ad failed :" + s );
                        listener.onAdViewAdLoadFailed( MaxAdapterError.NO_FILL );
                    }

                    @Override
                    public void onAdClosed() {
                        listener.onAdViewAdCollapsed();
                    }

                });

                //
                // GDPR options
                //
                // Set user consent state
                if ( getWrappingSdk().getConfiguration().getConsentDialogState() == AppLovinSdkConfiguration.ConsentDialogState.APPLIES )
                {

                    Boolean hasUserConsent = getPrivacySetting( "hasUserConsent", parameters );
                    if ( hasUserConsent != null )
                    {
                        adViewBIDView.setGDPR2(hasUserConsent ? 1 : 0, user_GDPR);
                    }
                }
                else if ( getWrappingSdk().getConfiguration().getConsentDialogState() == AppLovinSdkConfiguration.ConsentDialogState.DOES_NOT_APPLY )
                {
                    //adViewBIDView.setGDPR2(1,user_GDPR);
                }


                adViewBIDView.setRefreshTime(-1);
                //adViewBIDView.setTestMode(true);


    }

    @Override
    public void loadInterstitialAd(final MaxAdapterResponseParameters parameters, final Activity activity,
                                   final MaxInterstitialAdapterListener listener)
    {
        final String zoneId = parameters.getThirdPartyAdPlacementId();
        final String bidResponse = parameters.getBidResponse();
        Log.i( "= loadInterstitialAd =",
                "Loading " + ( TextUtils.isEmpty( bidResponse ) ? "bidding " : "" ) + " interstitial ad for zone id " + zoneId + "..." );

        if ( !isAdVgConfigured() )
        {
            log( "AdView SDK is not initialized" );

            listener.onInterstitialAdLoadFailed( MaxAdapterError.NOT_INITIALIZED );
            return;
        }

        /////////////////// advg porting ///////////////////////////
        //===================================

                adInstlBIDView = new AdViewInstlManager(activity,
                        appId,
                        zoneId,
                        true 
                );

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

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

                    }
                    @Override
                    public void onAdClicked() {
                        Log.i( "loadInterstitialAd","==advg == Interstitial clicked ====" );
                        listener.onInterstitialAdClicked();
                    }

                    @Override
                    public void onAdDisplayed() {
                        log( "==advg == Interstitial displayed ====" );
                        listener.onInterstitialAdDisplayed();
                    }

                    @Override
                    public void onAdReceived() {
                        log( "==advg ===== Interstitial loaded" );
                        listener.onInterstitialAdLoaded();
                    }

                    @Override
                    public void onAdFailedReceived(String s) {
                        log( "== advg === Interstitial failed to fill for zone: " + zoneId + "=====");
                        listener.onInterstitialAdLoadFailed( MaxAdapterError.NO_FILL );
                    }

                    @Override
                    public void onAdClosed() {
                        log( "== advg === Interstitial hidden ====" );
                        listener.onInterstitialAdHidden();
                        adInstlBIDView = null;
                    }

                });

                


    }

    @Override
    public void showInterstitialAd(final MaxAdapterResponseParameters parameters, final Activity activity, final MaxInterstitialAdapterListener listener)
    {
        Log.i( "showInterstitialAd","==== advg == Showing interstitial ad... ====" );

        ///advg porting ////
        // Show your interstitial ad.

        if ( adInstlBIDView == null )
        {
            Log.i( "showInterstitialAd","Interstitial ad not ready" );
            listener.onInterstitialAdDisplayFailed( MaxAdapterError.UNSPECIFIED );
            return;
        }

//        if ( adInstlBIDView.isExpired() )
//        {
//            log( "Interstitial ad is expired" );
//
//            MaxAdapterError adapterError = MaxAdapterError.AD_EXPIRED;
//            listener.onInterstitialAdDisplayFailed( adapterError );
//
//            return;
//        }

        final boolean success = adInstlBIDView.showInstl(activity);
        if ( !success )
        {
            Log.i("showInterstitialAd", "==== advg === Interstitial ad failed to display  ====" );
            listener.onInterstitialAdDisplayFailed( MaxAdapterError.UNSPECIFIED );
        }
    }


    @Override
    public void loadRewardedAd(final MaxAdapterResponseParameters parameters, final Activity activity, final MaxRewardedAdapterListener listener)
    {
        final String zoneId = parameters.getThirdPartyAdPlacementId();
        final String bidResponse = parameters.getBidResponse();
        d( "Loading " + ( TextUtils.isEmpty( bidResponse ) ? "bidding " : "" ) + " rewarded ad for zone id " + zoneId + "..." );

        if ( !isAdVgConfigured())
        {
            log( "AdVG SDK is not initialized" );

            listener.onRewardedAdLoadFailed( MaxAdapterError.NOT_INITIALIZED );
            return;
        }

        //////// advg porting ///////////////////
        ///=======================================
                adViewVideoListener = new AdViewVideoListener() {
                    @Override
                    public void onFailedReceivedVideo(String error) {
                        //Log.i(TAG, "!!!!![admob-adview] onFailedRecievedVideo:"+error + "!!!!");
                        //medAdLoadCallBack.onFailure(error.toString());
                        d( "==advg == Rewarded ad failed to fill for zone: " + zoneId + "=====");
                        listener.onRewardedAdLoadFailed( MaxAdapterError.NO_FILL );
                    }
                    @Override
                    public void onVideoStartPlayed() {
                        d( "=== advg == Rewarded video ad play start ===" );
                        //impression
                        listener.onRewardedAdDisplayed();
                        //start play
                        listener.onRewardedAdVideoStarted();
                    }
                    @Override
                    public void onVideoFinished() {
                        d( "=== advg == Rewarded video ad play finished ===" );
                        listener.onRewardedAdVideoCompleted();
                    }
                    @Override
                    public void onVideoClosed() {

                        //listener.onRewardedAdVideoCompleted();
//                if ( hasGrantedReward || shouldAlwaysRewardUser() )
//                {
//                    final MaxReward reward = getReward();
//                    log( "Rewarded user with reward: " + reward );
//                    listener.onUserRewarded( reward );
//                }

                        d( "=== advg == Rewarded ad hidden ===" );
                        listener.onRewardedAdHidden();
                    }
                    @Override
                    public void onPlayedError(String arg0) {
                        d( "==advg == Rewarded ad failed to fill for zone: " + zoneId + "=====");
                        listener.onRewardedAdLoadFailed( MaxAdapterError.NO_FILL );

                    }
                    @Override
                    public void onReceivedVideo(String arg0) {

                        //Log.i(TAG, "++++ [admob-adview] onRecievedVideo:"+arg0 + "++++");
                        d( "=== advg == Rewarded ad loaded ====" );

                    }
                    @Override
                    public void onVideoReady() {
                        //Log.i(TAG, "++++ [admob-adview] onVideoReady +++");
                        d( "=== advg== Rewarded ad loaded & ready ===" );
//                listener.onRewardedAdDisplayed();
//                listener.onRewardedAdVideoStarted();
                    }
                    @Override
                    public void onVideoClicked(int x, int y) {

                        log( "=== advg === Rewarded ad clicked ====" );
                        listener.onRewardedAdClicked();
                    }
                };

                listener.onRewardedAdLoaded(); //此处直接发送loaded，以便之后进行播放

    }


    @Override
    public void showRewardedAd(final MaxAdapterResponseParameters parameters, final Activity activity,
                               final MaxRewardedAdapterListener listener)
    {
        d( "==advg == Showing rewarded ad... ==" );

        if ( adViewVideoListener == null )
        {
            log( "=== advg == Rewarded ad not ready ===" );
            listener.onRewardedAdDisplayFailed( MaxAdapterError.UNSPECIFIED );

            return;
        }
//        if ( loadedRewardedAd.isExpired() )
//        {
//            log( "Rewarded ad is expired" );
//
//            MaxAdapterError adapterError = MaxAdapterError.AD_EXPIRED;
//            listener.onRewardedAdDisplayFailed( adapterError );
//
//            return;
//        }

        // Configure userReward from server.
        configureReward( parameters );

        String video_posid = parameters.getThirdPartyAdPlacementId();
        videoManager = new AdViewVideoManager(
                //this,
                activity,
                appId,
                video_posid,
                adViewVideoListener,
                false);

        //videoManager.setGDPR2(1,Gdpr);
        videoManager.setVideoOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        //videoManager.setAutoPlay(false);
    }

    @Override
    public void loadNativeAd(final MaxAdapterResponseParameters parameters, final Activity activity, final MaxNativeAdAdapterListener listener)
    {
        final String posid = parameters.getThirdPartyAdPlacementId();
        d( "Loading native ad for ad id: " + posid + "..." );

        final Bundle serverParameters = parameters.getServerParameters();
        //////////////////
        advListener = new com.advg.loader.loaderInterface.AdViewNativeListener() {
            @Override
            public void onNativeAdReceiveFailed(String arg0) {
                MaxAdapterError error = MaxAdapterError.NO_FILL;//toMaxError( errorCode );
                e( "Native failed to load: " + error );

                nativeAdFaild = true;
                listener.onNativeAdLoadFailed( MaxAdapterError.NO_FILL );

            }
            /**
             * received success
             *
             * @param nativeAdList
             *            type is List<HashMap<String,Object>>，response is ：
             *            title--> title
             *            adImage-->large image url
             *            adIcon--> Icon image url
             *            adFlagLogo--> logo
             *            desc--> description text
             *            sec_description--> text 2
             * note: title,adImage,adIcon,desc is needed
             */
            @Override
            public void onNativeAdReceived(List nativeAdList) {
                Log.i("AdNativeActivity", "onNativeAdReceived");
                d( "Native ad loaded" );

                final String templateName = BundleUtils.getString( "template", "", serverParameters );
                final boolean isTemplateAd = AppLovinSdkUtils.isValidString( templateName );

                ///////////////////////////////////////////////////
                for(int i = 0; i < nativeAdList.size(); i++) {
                    //holder = new ViewHolder();
                    final HashMap<String, Object> nativeAd = (HashMap) nativeAdList.get(i);
                    if (!nativeAd.toString().contains("videoUrl")) {
                        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();
                        }

                        //privacy image
                        if (null != nativeAd.get("privacy_image")) {
                            String url = ((CharSequence) nativeAd.get("privacy_image")).toString();
                        }
                    } else {
                        String videoURL = ((CharSequence) nativeAd.get("videoUrl")).toString();
                    }

                    new Thread(new Runnable(){
                        String imgURL;
                        String iconURL;
                        String str_title,str_desc;
                        String str_sec_desc,native_adid;
                        ImageView mainImageView;
                        @Override
                        public void run() {
                            try {

                                if (null != nativeAd.get("adImage")) {
                                    imgURL = ((CharSequence) nativeAd.get("adImage")).toString();
                                }
                                if (null != nativeAd.get("adIcon")) {
                                    iconURL = ((CharSequence) nativeAd.get("adIcon")).toString();
                                }
                                if (null != nativeAd.get("title")) {
                                    str_title = ((CharSequence) nativeAd.get("title")).toString();
                                }
                                if (null != nativeAd.get("description")) {
                                    str_desc = ((CharSequence) nativeAd.get("description")).toString();
                                }
                                if (null != nativeAd.get("sec_description")) {
                                    str_sec_desc = ((CharSequence) nativeAd.get("sec_description")).toString();
                                }
                                if (null != nativeAd.get("adId")) {
                                    native_adid = ((CharSequence) nativeAd.get("adId")).toString();
                                }

                                MaxNativeAd.MaxNativeAdImage iconImage = null;

                                if ( iconURL.length() > 0 )
                                {
                                    Drawable icon;
                                    icon = loadImageFromNetwork(iconURL);
                                    iconImage = new MaxNativeAd.MaxNativeAdImage( icon );
                                }
                                View mediaView = null;

                                if (imgURL.length() > 0) {

                                    mainImageView = new ImageView( activity );
                                    //mainImageView.setImageDrawable( image.getDrawable() );
                                    Drawable img;
                                    img = loadImageFromNetwork(imgURL);
                                    //mainImageView.setImageURI(Uri.parse(imgURL));
                                    mainImageView.setImageDrawable( img );
                                    mediaView = mainImageView;
                                }

                                //click report 
                                mainImageView.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        if (null != v) {
                                            
                                            if (null != adViewNative && !nativeAdFaild) {
                                                adViewNative.reportClick(
                                                        v,
                                                        native_adid,
                                                        (int) 0,
                                                        (int) 0);
                                                //send click
                                                listener.onNativeAdClicked();
                                            }
                                        }
                                    }
                                });

                                MaxNativeAd.Builder builder = new MaxNativeAd.Builder()
                                        .setAdFormat( MaxAdFormat.NATIVE )
                                        .setTitle( str_title )
                                        .setAdvertiser( str_sec_desc )
                                        .setBody( str_desc )
                                        .setCallToAction( "Take Action!" )
                                        .setIcon( iconImage )
                                        .setMediaView( mediaView );

                                MaxNativeAd maxNativeAd = new MaxNativeAd( builder );

                                listener.onNativeAdLoaded( maxNativeAd, null );


                                new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (!nativeAdFaild) {
                                            adViewNative.reportImpression(mainImageView, native_adid);
                                            //send impression
                                            listener.onNativeAdDisplayed(null);
                                        }
                                    }
                                },1000);

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

                }
                ////////////////end wilder //////////////////////////
            }
            @Override
            public void onDownloadStatusChange(int arg0) {

            }
            @Override
            public void onNativeAdClosed(View view) {

            }
        };
                
                adViewNative = new AdViewNativeManager(activity,
                        appId,
                        posid,
                        advListener
                );
                ////////////////////
                //adViewNative.setGDPR2(1, Gdpr);
                //adViewNative.setTestMode(true);

                nativeAdFaild = false;
                adViewNative.requestAd();

    }

    //////////////////////////////////////////////////////////////////////////////////
    /////////////////////////// region Helper Methods ///////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////
    private boolean isAdVgConfigured()
    {
        return true; 
    }

    /**
     * Gets a String array of zone ids from the server parameters.
     * Note that the SDK converts string arrays into an ArrayList to be stored in the server parameters Bundle.
     */
    private String[] getZoneIds(MaxAdapterParameters parameters)
    {
        final List<String> rawZoneIds = parameters.getServerParameters().getStringArrayList( "zone_ids" );
        if ( rawZoneIds == null || rawZoneIds.size() == 0 ) return new String[0];

        final String[] zoneIds = new String[rawZoneIds.size()];
        for ( int i = 0; i < rawZoneIds.size(); i++ )
        {
            zoneIds[i] = rawZoneIds.get( i );
        }

        return zoneIds;
    }


    private int sizeFromAdFormat(final MaxAdFormat adFormat)
    {
        ////////// advg changed ///////////////
        if ( adFormat == MaxAdFormat.BANNER )
        {
            return AdViewBannerManager.BANNER_AUTO_FILL;
        }
        else if ( adFormat == MaxAdFormat.LEADER )
        {
            return AdViewBannerManager.BANNER_SMART; 
        }
        else if ( adFormat == MaxAdFormat.MREC )
        {
            return AdViewBannerManager.BANNER_MREC;
        }
        else
        {
            AppLovinSdkUtils.Size sz = adFormat.getSize();
            if (sz.getWidth() == 320 && sz.getHeight() == 50) {
                //if (widthInPixels == 320 && heightInPixels == 50) {
                return AdViewBannerManager.BANNER_SMART;
            }
            throw new IllegalArgumentException( "Invalid ad format: " + adFormat );
        }

    }

    private Boolean getPrivacySetting(final String privacySetting, final MaxAdapterParameters parameters)
    {
        try
        {
            // Use reflection because compiled adapters have trouble fetching `boolean` from old SDKs and `Boolean` from new SDKs (above 9.14.0)
            Class<?> parametersClass = parameters.getClass();
            Method privacyMethod = parametersClass.getMethod( privacySetting );
            return (Boolean) privacyMethod.invoke( parameters );
        }
        catch ( Exception exception )
        {
            log( "Error getting privacy setting " + privacySetting + " with exception: ", exception );
            return ( AppLovinSdk.VERSION_CODE >= 9140000 ) ? null : false;
        }
    }

    //endregion

    private boolean hasRequiredAssets(final boolean isTemplateAd, final HashMap<String, Object> nativeAd)
    {
        if ( isTemplateAd )
        {
            if (null != nativeAd.get("title"))
            return true;
        }
        return false;
    }

    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();
            }

            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;


    }


}
