package com.ads.cal.calculator;

import static com.ads.cal.calculator.utils.EventIdUtils.AD_HOME_NATIVE_CLK;
import static com.ads.cal.calculator.utils.EventIdUtils.AD_HOME_NATIVE_CLOSE;
import static com.ads.cal.calculator.utils.EventIdUtils.AD_HOME_NATIVE_EXP;
import static com.ads.cal.calculator.utils.EventIdUtils.AD_HOME_NATIVE_LOAD_FAILED;
import static com.ads.cal.calculator.utils.EventIdUtils.AD_HOME_NATIVE_LOAD_SUCCESS;
import static com.ads.cal.calculator.utils.EventIdUtils.AD_HOME_NATIVE_START_LOAD;
import static com.ads.cal.calculator.utils.EventIdUtils.AD_OPEN_EXP;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.ads.cal.calculator.activity.CalculatorActivity;
import com.ads.cal.calculator.activity.CompassActivity;
import com.ads.cal.calculator.activity.DecibelActivity;
import com.ads.cal.calculator.activity.SettingActivity;
import com.ads.cal.calculator.base.BaseActivity;
import com.ads.cal.calculator.nativetemplates.NativeTemplateStyle;
import com.ads.cal.calculator.nativetemplates.TemplateView;
import com.ads.cal.calculator.utils.EventIdUtils;
import com.ads.cal.calculator.utils.FireBaseAnalyticsUtils;
import com.ads.cal.calculator.utils.LogUtils;
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.VideoController;
import com.google.android.gms.ads.VideoOptions;
import com.google.android.gms.ads.nativead.MediaView;
import com.google.android.gms.ads.nativead.NativeAd;
import com.google.android.gms.ads.nativead.NativeAdOptions;
import com.google.android.gms.ads.nativead.NativeAdView;

import java.util.Locale;

public class MainActivity extends BaseActivity {
//    private static final String ADMOB_AD_UNIT_ID = "ca-app-pub-3940256099942544/2247696110";
    private NativeAd nativeAd;


    @Override
    protected String getPageExpEventId() {
        return EventIdUtils.HOME_EXP;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        findViewById(R.id.calculator).setOnClickListener(v -> {
            CalculatorActivity.instance(MainActivity.this);
            FireBaseAnalyticsUtils.init().send(EventIdUtils.HOME_CALCULATOR_CLK);
        });
        findViewById(R.id.compress).setOnClickListener(v -> {
            CompassActivity.instance(MainActivity.this);
            FireBaseAnalyticsUtils.init().send(EventIdUtils.HOME_COMPASS_CLK);
        });
        findViewById(R.id.decibel).setOnClickListener(v -> {
            DecibelActivity.instance(MainActivity.this);
            FireBaseAnalyticsUtils.init().send(EventIdUtils.HOME_DECIBEL_CLK);
        });
        findViewById(R.id.setting).setOnClickListener(view -> {
            SettingActivity.invoke(MainActivity.this);
            FireBaseAnalyticsUtils.init().send(EventIdUtils.HOME_SETTING_CLK);
        });
    }

    @Override
    protected void initData() {
//        refreshAd();
    }


    private void refreshAd() {
//        AdLoader.Builder builder = new AdLoader.Builder(this, ADMOB_AD_UNIT_ID);
//        // OnLoadedListener implementation.
//        builder.forNativeAd(nativeAd -> {
//            // If this callback occurs after the activity is destroyed, you must call
//            // destroy and return or you may get a memory leak.
//            boolean isDestroyed = isDestroyed();
//            if (isDestroyed || isFinishing() || isChangingConfigurations()) {
//                nativeAd.destroy();
//                return;
//            }
//            // You must call destroy on old ads when you are done with them,
//            // otherwise you will have a memory leak.
//            if (MainActivity.this.nativeAd != null) {
//                MainActivity.this.nativeAd.destroy();
//            }
//            MainActivity.this.nativeAd = nativeAd;
//            FrameLayout frameLayout = findViewById(R.id.ad_layout);
//            NativeAdView adView = (NativeAdView) getLayoutInflater().inflate(R.layout.ad_unified, frameLayout, false);
//            populateNativeAdView(nativeAd, adView);
//            frameLayout.removeAllViews();
//            frameLayout.addView(adView);
//            NativeTemplateStyle styles = null;
//            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
//                styles = new NativeTemplateStyle.Builder().withMainBackgroundColor(new ColorDrawable(getColor(R.color.white))).build();
//            } else {
//                styles = new NativeTemplateStyle.Builder().withMainBackgroundColor(new ColorDrawable(getResources().getColor(R.color.white))).build();
//            }
//            TemplateView template = findViewById(R.id.ad_layout);
//            template.setStyles(styles);
//            template.setNativeAd(nativeAd);
//        });

//        VideoOptions videoOptions = new VideoOptions.Builder().setStartMuted(false).build();
//
//        NativeAdOptions adOptions = new NativeAdOptions.Builder().setVideoOptions(videoOptions).build();
//
//        builder.withNativeAdOptions(adOptions);
//
//        AdLoader adLoader = builder.withAdListener(new AdListener() {
//            @Override
//            public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
//                String error = String.format(Locale.getDefault(), "domain: %s, code: %d, message: %s", loadAdError.getDomain(), loadAdError.getCode(), loadAdError.getMessage());
//                LogUtils.log("home native onAdLoad  Failed     " +  error);
//                FireBaseAnalyticsUtils.init().send(AD_HOME_NATIVE_LOAD_FAILED);
//            }
//
//            @Override
//            public void onAdLoaded() {
//                super.onAdLoaded();
//                LogUtils.log("home native onAdLoaded");
//                FireBaseAnalyticsUtils.init().send(AD_HOME_NATIVE_LOAD_SUCCESS);
//            }
//
//            @Override
//            public void onAdClicked() {
//                super.onAdClicked();
//                LogUtils.log("home native onAdClicked");
//                FireBaseAnalyticsUtils.init().send(AD_HOME_NATIVE_CLK);
//            }
//
//            @Override
//            public void onAdClosed() {
//                super.onAdClosed();
//                LogUtils.log("home native onAdClosed");
//                FireBaseAnalyticsUtils.init().send(AD_HOME_NATIVE_CLOSE);
//            }
//
//            @Override
//            public void onAdImpression() {
//                super.onAdImpression();
//                LogUtils.log("home native onAdImpression");
//                FireBaseAnalyticsUtils.init().send(AD_HOME_NATIVE_EXP);
//            }
//
//            @Override
//            public void onAdOpened() {
//                super.onAdOpened();
//            }
//
//        }).build();
//
//        adLoader.loadAd(new AdRequest.Builder().build());
//        FireBaseAnalyticsUtils.init().send(AD_HOME_NATIVE_START_LOAD);
//        LogUtils.log("home native onAdLoad  start     " );
    }

    private void populateNativeAdView(NativeAd nativeAd, NativeAdView adView) {
        // 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.
                    LogUtils.log("Video status: Video playback has ended.");
                    super.onVideoEnd();
                }
            });
        } else {
            LogUtils.log("Video status: Ad does not contain a video asset.");
        }
    }


    public static void invoke(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }
}