/*
 *    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.adviewkotlindemo.activities.ads.admob

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.adview.sdk.NativeAdUnit
import com.adview.sdk.admob.AdviewNativeAdapter
import com.adview.mobile.adviewkotlindemo.activities.BaseAdActivity
import com.adview.mobile.adviewkotlindemo.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

class AdMobNativeActivity : BaseAdActivity() {

    companion object {
        const val AD_UNIT_ID = "ca-app-pub-7283949697136772/2362910582" //admob native
        const val CONFIG_ID = "POSIDjdk0claa5fec" //native official
    }

    private var nativeAd: NativeAd? = null
    private var testSizeDp = 320

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        createAd()
    }

    private fun createAd() {
        val nativeAdOptions = NativeAdOptions
            .Builder()
            .build()
        val adLoader = AdLoader
            .Builder(this, AD_UNIT_ID)
            .forNativeAd { ad: NativeAd ->
                nativeAd = ad
                createCustomView(adWrapperView, nativeAd!!)
            }
            .withAdListener(object : AdListener() {
                override fun onAdFailedToLoad(adError: LoadAdError) {
                    Log.e("AdMobNative", "==== Error: ${adError.message} ====")
                }
            })
            .withNativeAdOptions(nativeAdOptions)
            .build()

        val extras = Bundle()
        val adRequest = AdRequest
            .Builder()
            .addNetworkExtrasBundle(AdviewNativeAdapter::class.java, extras)
            .build()

        val nativeAdUnit = NativeAdUnit(CONFIG_ID)

        configureNativeAdUnit(nativeAdUnit)

        nativeAdUnit.fetchDemand(extras) { resultCode ->
            Log.d("AdMobNative", "Fetch demand result: $resultCode")

            /** For mediation use loadAd() not loadAds() */
            adLoader.loadAd(adRequest)
        }
    }

    private fun configureNativeAdUnit(nativeAdUnit: NativeAdUnit) {

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

    private fun createCustomView(wrapper: ViewGroup, nativeAd: NativeAd) {
        wrapper.removeAllViews()
        val binding = ViewNativeAdAdMobBinding.inflate(LayoutInflater.from(wrapper.context))

        // --- 1. test size (dp) ---
        val density = resources.displayMetrics.density
        val sizePx = (testSizeDp * density).toInt()

        // root layout
        // note: AdMob NativeAdView must set LayoutParams can take effect in root
        binding.root.layoutParams = FrameLayout.LayoutParams(sizePx,
            ViewGroup.LayoutParams.WRAP_CONTENT
        ).apply {
            gravity = android.view.Gravity.CENTER
        }

        // background color
        binding.root.setBackgroundColor(android.graphics.Color.WHITE)

        binding.apply {
            tvHeadline.text = nativeAd.headline
            tvBody.text = nativeAd.body
            imgIco.setImageDrawable(nativeAd.icon?.drawable)
            imgMedia.mediaContent = nativeAd.mediaContent
            
            if (nativeAd.callToAction == null) {
                btnCTA.visibility = View.INVISIBLE
            } else {
                btnCTA.visibility = View.VISIBLE
                btnCTA.text = nativeAd.callToAction
            }
        }

        binding.viewNativeWrapper.apply {
            headlineView = binding.tvHeadline
            bodyView = binding.tvBody
            iconView = binding.imgIco
            mediaView = binding.imgMedia
            callToActionView = binding.btnCTA
            setNativeAd(nativeAd)
        }

        wrapper.addView(binding.root)
    }


    override fun onDestroy() {
        super.onDestroy()
        nativeAd?.destroy()
    }

}
