/*
 *    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.admob;

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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.adview.sdk.NativeAdUnit;
import com.adview.sdk.admob.AdviewNativeAdapter;
import com.adview.mobile.javademo.activities.BaseAdActivity;
import com.adview.mobile.javademo.databinding.ViewNativeAdAdMobBinding;
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.NativeAd;
import com.google.android.gms.ads.nativead.NativeAdOptions;

import java.util.ArrayList;

public class AdMobNativeActivity extends BaseAdActivity {

    private static final String AD_UNIT_ID = "ca-app-pub-7283949697136772/2362910582";
    private static final String CONFIG_ID = "POSIDjdk0claa5fec"; //native official

    private NativeAd nativeAd;
    private int testSizeDp = 320;

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

        createAd();
    }

    private void createAd() {
        NativeAdOptions nativeAdOptions = new NativeAdOptions.Builder().build();
        AdLoader adLoader = new AdLoader.Builder(this, AD_UNIT_ID)
                .forNativeAd(ad -> {
                    nativeAd = ad;
                    createCustomView(getAdWrapperView(), nativeAd);
                })
                .withAdListener(new AdListener() {
                    @Override
                    public void onAdFailedToLoad(@NonNull LoadAdError adError) {
                        Log.e("AdMobNative", "==== Error: " + adError.getMessage() + " ====");
                    }
                })
                .withNativeAdOptions(nativeAdOptions)
                .build();

        Bundle extras = new Bundle();
        AdRequest adRequest = new AdRequest.Builder()
                .addNetworkExtrasBundle(AdviewNativeAdapter.class, extras)
                .build();

        NativeAdUnit nativeAdUnit = configureNativeAdUnit();

        nativeAdUnit.fetchDemand(extras, resultCode -> {
            Log.d("AdMobNative", "Fetch demand result: " + resultCode);
            adLoader.loadAd(adRequest);
        });
    }

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

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

        return adUnit;
    }

    private void createCustomView(ViewGroup wrapper, NativeAd nativeAd) {
        wrapper.removeAllViews();
        ViewNativeAdAdMobBinding binding = ViewNativeAdAdMobBinding.inflate(LayoutInflater.from(wrapper.getContext()));

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

        // Adjust to WRAP_CONTENT to fit content and use white background
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(sizePx, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.gravity = Gravity.CENTER;
        binding.getRoot().setLayoutParams(lp);
        binding.getRoot().setBackgroundColor(Color.WHITE);

        binding.tvHeadline.setText(nativeAd.getHeadline());
        binding.tvBody.setText(nativeAd.getBody());
        if (nativeAd.getIcon() != null) {
            binding.imgIco.setImageDrawable(nativeAd.getIcon().getDrawable());
        }
        binding.imgMedia.setMediaContent(nativeAd.getMediaContent());

        // Bind CTA text and visibility
        if (nativeAd.getCallToAction() == null) {
            binding.btnCTA.setVisibility(View.INVISIBLE);
        } else {
            binding.btnCTA.setVisibility(View.VISIBLE);
            binding.btnCTA.setText(nativeAd.getCallToAction());
        }

        binding.viewNativeWrapper.setHeadlineView(binding.tvHeadline);
        binding.viewNativeWrapper.setBodyView(binding.tvBody);
        binding.viewNativeWrapper.setIconView(binding.imgIco);
        binding.viewNativeWrapper.setMediaView(binding.imgMedia);
        binding.viewNativeWrapper.setCallToActionView(binding.btnCTA);
        binding.viewNativeWrapper.setNativeAd(nativeAd);

        wrapper.addView(binding.getRoot());
    }

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