/*
 *    Copyright 2018-2019 adview.com, 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.adview.mobile.javademo.activities.ads.applovin;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.Nullable;

import com.adview.sdk.NativeAdUnit;
import com.adview.mobile.javademo.R;
import com.adview.mobile.javademo.activities.BaseAdActivity;
import com.applovin.mediation.MaxAd;
import com.applovin.mediation.MaxError;
import com.applovin.mediation.nativeAds.MaxNativeAdListener;
import com.applovin.mediation.nativeAds.MaxNativeAdLoader;
import com.applovin.mediation.nativeAds.MaxNativeAdView;
import com.applovin.mediation.nativeAds.MaxNativeAdViewBinder;


public class AppLovinMaxNativeActivity extends BaseAdActivity {

    private static final String TAG = "AppLovinMaxNative";
    public static final String AD_UNIT_ID = "bb7236241e4b4d7b"; //max unit
    private static final String CONFIG_ID = "POSIDjdk0claa5fec"; //native official

    private MaxNativeAdLoader nativeAdLoader;
    private int testSizeDp = 320;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        createAd();
    }

    private void createAd() {
        nativeAdLoader = new MaxNativeAdLoader(AD_UNIT_ID, this);
        nativeAdLoader.setNativeAdListener(new MaxNativeAdListener() {
            @Override
            public void onNativeAdLoaded(@Nullable MaxNativeAdView nativeAdView, MaxAd nativeAd) {
                Log.d(TAG, "=== Native ad loaded: " + nativeAd + " ===");

                if (nativeAdView == null) return;

                float density = getResources().getDisplayMetrics().density;
                int sizePx = (int) (testSizeDp * density);

                // Use WRAP_CONTENT for height to match Kotlin version and white background
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(sizePx, ViewGroup.LayoutParams.WRAP_CONTENT);
                params.gravity = Gravity.CENTER;
                nativeAdView.setLayoutParams(params);

                nativeAdView.setBackgroundColor(Color.WHITE);

                String ctaText = nativeAd.getNativeAd().getCallToAction();
                View ctaButton = nativeAdView.findViewById(R.id.btnCallToAction);
                if (ctaText == null || ctaText.isEmpty()) {
                    if (ctaButton != null) ctaButton.setVisibility(View.GONE);
                } else {
                    if (ctaButton != null) ctaButton.setVisibility(View.VISIBLE);
                }

                getAdWrapperView().removeAllViews();
                getAdWrapperView().addView(nativeAdView);
            }

            @Override
            public void onNativeAdLoadFailed(String adUnitId, MaxError error) {
                Log.e(TAG, "=== Failed to load: " + adUnitId + " ===");
            }

            @Override
            public void onNativeAdClicked(MaxAd ad) {
                Log.d(TAG, "=== Native ad clicked ===");
            }
        });

        NativeAdUnit nativeAdUnit = configureNativeAdUnit();
        nativeAdUnit.fetchDemand(nativeAdLoader, resultCode -> {
            nativeAdLoader.loadAd(createNativeAdView());
        });
    }

    private NativeAdUnit configureNativeAdUnit() {
        NativeAdUnit nativeAdUnit = new NativeAdUnit(CONFIG_ID);

        nativeAdUnit.setContextType(NativeAdUnit.CONTEXT_TYPE.SOCIAL_CENTRIC);
        nativeAdUnit.setPlacementType(NativeAdUnit.PLACEMENTTYPE.CONTENT_FEED);
        nativeAdUnit.setContextSubType(NativeAdUnit.CONTEXTSUBTYPE.GENERAL_SOCIAL);

        return nativeAdUnit;
    }

    private MaxNativeAdView createNativeAdView() {
        MaxNativeAdViewBinder binder = new MaxNativeAdViewBinder.Builder(R.layout.view_native_ad_max)
                .setTitleTextViewId(R.id.tvHeadline)
                .setBodyTextViewId(R.id.tvBody)
                .setIconImageViewId(R.id.imgIco)
                .setMediaContentViewGroupId(R.id.frameMedia)
                .setCallToActionButtonId(R.id.btnCallToAction)
                .build();
        return new MaxNativeAdView(binder, this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (nativeAdLoader != null) {
            nativeAdLoader.destroy();
        }
    }
}
