/*
 *    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.applovin

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 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
import com.adview.mobile.adviewkotlindemo.activities.BaseAdActivity
import com.adview.mobile.adviewkotlindemo.R
import com.adview.sdk.NativeAdUnit

class AppLovinMaxNativeActivity : BaseAdActivity() {

    companion object {
        const val AD_UNIT_ID = "103e1eaa80898083" //max adunit
        const val CONFIG_ID = "POSIDjdk0claa5fec" //native official
    }

    private var nativeAdLoader: MaxNativeAdLoader? = null
    private var testSizeDp = 320 // size

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

        createAd()
    }

    private fun createAd() {
        nativeAdLoader = MaxNativeAdLoader(AD_UNIT_ID, this)
        nativeAdLoader?.setRevenueListener {}
        nativeAdLoader?.setNativeAdListener(object : MaxNativeAdListener() {
            override fun onNativeAdLoaded(nativeAdView: MaxNativeAdView?, nativeAd: MaxAd) {
                Log.d("AppLovinMaxNative", "=== Native ad loaded: $nativeAd ===")

                val view = nativeAdView ?: return
                
                // size (px) ---
                val density = resources.displayMetrics.density
                val sizePx = (testSizeDp * density).toInt()

                view.layoutParams = FrameLayout.LayoutParams(sizePx, ViewGroup.LayoutParams.WRAP_CONTENT).apply {
                    gravity = Gravity.CENTER //center
                }

                view.setBackgroundColor(android.graphics.Color.WHITE)

                // cta
                val ctaText = nativeAd.nativeAd?.callToAction
                val ctaButton = view.findViewById<View>(R.id.btnCallToAction)
                if (ctaText.isNullOrBlank()) {
                    ctaButton?.visibility = View.GONE
                } else {
                    ctaButton?.visibility = View.VISIBLE
                }

                adWrapperView.removeAllViews()
                adWrapperView.addView(nativeAdView)
            }

            override fun onNativeAdLoadFailed(p0: String, p1: MaxError) {
                Log.e("AppLovinMaxNative", "=== Failed to load: $p0 ===")
            }

            override fun onNativeAdClicked(p0: MaxAd) {}
        })

        val nativeAdUnit = configureNativeAdUnit()
        nativeAdUnit.fetchDemand(nativeAdLoader ?: return) {
            nativeAdLoader?.loadAd(createNativeAdView())
        }
    }


    private fun configureNativeAdUnit(): NativeAdUnit {
        val nativeAdUnit = 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 fun createNativeAdView(): MaxNativeAdView {
        val binder = 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 MaxNativeAdView(binder, this)
    }


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

}
