package com.retrytech.strangerapp.utils.ads;

import static android.content.ContentValues.TAG;
import static com.google.android.gms.ads.formats.NativeAdOptions.ADCHOICES_TOP_RIGHT;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Keep;
import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdLoader;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.nativead.NativeAdOptions;
import com.google.android.gms.ads.nativead.NativeAdView;
import com.retrytech.strangerapp.R;
import com.retrytech.strangerapp.utils.SessionManager;

@Keep
public class CustomNativeAds {
    private final boolean isEnabledAds = true;
    private final Activity context;
    private final SessionManager sessionManager;
    private final LinearLayout adsContainer;
    private final int admobNative;


    public CustomNativeAds(Activity context, LinearLayout adsContainer, int admobNative) {
        this.context = context;
        sessionManager = new SessionManager(context);
        this.adsContainer = adsContainer;
        this.admobNative = admobNative;
        initAds();
    }

    private void initAds() {
        loadNativeAds();
    }


    @SuppressLint("VisibleForTests")
    private void loadNativeAds() {


        AdLoader.Builder builder;
        builder = new AdLoader.Builder(context, sessionManager.getAppSettings().getAdmobs().getNativeId());
        // A native ad loaded successfully, check if the ad loader has finished loading
        // and if so, insert the ads into the list.
        // A native ad failed to load, check if the ad loader has finished loading
        // and if so, insert the ads into the list.
        AdLoader adLoader = builder.forNativeAd(
                        unifiedNativeAd -> {
                            Log.d(TAG, "onUnifiedNativeAdLoaded: ");
                            if (isEnabledAds) {
                                showAdmobAds(unifiedNativeAd);
                            }
                            // A native ad loaded successfully, check if the ad loader has finished loading
                            // and if so, insert the ads into the list.
                        }).withAdListener(
                        new AdListener() {

                            @Override
                            public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                                super.onAdFailedToLoad(loadAdError);
                                Log.e(TAG, "The previous native ad failed to load. Attempting to"
                                        + " load another." + loadAdError.getCode());


                            }
                        })
                .withNativeAdOptions(new NativeAdOptions.Builder()
                        .setRequestCustomMuteThisAd(true)
                        .setAdChoicesPlacement(ADCHOICES_TOP_RIGHT)
                        .build()).build();


        adLoader.loadAds(new AdRequest.Builder().build(), 1);
    }

    private void showAdmobAds(com.google.android.gms.ads.nativead.NativeAd unifiedNativeAd) {
        if (context != null) {
            View view = LayoutInflater.from(context).inflate(admobNative, null, false);
            NativeAdView adView = view.findViewById(R.id.ad_view);

            // The MediaView will display a video asset if one is present in the ad, and the
//            // first image asset otherwise.
//            adView.setMediaView(adView.findViewById(R.id.ad_media));

            // Register the view used for each individual asset.
            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));
            adsContainer.removeAllViews();
            adsContainer.addView(view, 0);
            populateNativeAdView(unifiedNativeAd, adView);
        }
    }


    private void populateNativeAdView(com.google.android.gms.ads.nativead.NativeAd nativeAd,
                                      NativeAdView adView) {
        if (adView == null || context == null || context.isDestroyed()) return;
        if (adView.getHeadlineView() != null) {
            ((TextView) adView.getHeadlineView()).setText(nativeAd.getHeadline());
        }
        if (adView.getBodyView() != null) {
            ((TextView) adView.getBodyView()).setText(nativeAd.getBody());
        }
        if (adView.getCallToActionView() != null) {
            ((Button) adView.getCallToActionView()).setText(nativeAd.getCallToAction());
        }

        // These assets aren't guaranteed to be in every UnifiedNativeAd, so it's important to
        // check before trying to display them.
        com.google.android.gms.ads.nativead.NativeAd.Image icon = nativeAd.getIcon();

        if (icon == null) {
            if (adView.getIconView() != null) {
                adView.getIconView().setVisibility(View.INVISIBLE);
            }
        } else if (isEnabledAds) {
            if (adView.getIconView() != null) {
                Glide.with(context)
                        .load(icon.getDrawable())
                        .circleCrop()
                        .into((ImageView) adView.getIconView());
                adView.getIconView().setVisibility(View.VISIBLE);
            }
        }
        if (adView.getPriceView() != null) {
            if (nativeAd.getPrice() == null) {
                adView.getPriceView().setVisibility(View.INVISIBLE);
            } else {
                adView.getPriceView().setVisibility(View.VISIBLE);
                ((TextView) adView.getPriceView()).setText(nativeAd.getPrice());
            }
        }
        if (adView.getStoreView() != null) {
            if (nativeAd.getStore() == null) {
                adView.getStoreView().setVisibility(View.INVISIBLE);
            } else {
                adView.getStoreView().setVisibility(View.VISIBLE);
                ((TextView) adView.getStoreView()).setText(nativeAd.getStore());
            }
        }
        adView.setNativeAd(nativeAd);

    }

}
