/*
 *    Copyright 2018-2019 Adview.org, 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.inapp

import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.widget.FrameLayout
import com.adview.sdk.AdSize
import com.adview.sdk.api.exceptions.AdException
import com.adview.sdk.api.rendering.BannerView
import com.adview.sdk.api.rendering.listeners.BannerViewListener
import com.adview.mobile.adviewkotlindemo.activities.BaseAdActivity
import com.adview.sdk.AdviewMobile

class InAppDisplayBanner320x50Activity : BaseAdActivity() {

    companion object {
        const val CONFIG_ID = "POSID0wbfijwzm430" //official line
        const val WIDTH = 320
        const val HEIGHT = 50
    }

    private var adView: BannerView? = null

    private var configId = CONFIG_ID

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

        createAd()
    }

    private fun createAd() {
        adView = BannerView(
            this,
            configId,
            AdSize(WIDTH, HEIGHT)
        )

        //center
        val density = resources.displayMetrics.density
        val widthPx = ( WIDTH * density).toInt()
        val heightPx = (HEIGHT * density).toInt()
        val layoutParams = FrameLayout.LayoutParams(widthPx, heightPx).apply {
            gravity = Gravity.CENTER_HORIZONTAL
        }

        adWrapperView.addView(adView, layoutParams)

        adView?.setBannerListener(object : BannerViewListener {
            override fun onAdFailed(bannerView: BannerView?, exception: AdException?) {
                Log.e("InAppDisplayBanner", "Ad failed: ${exception?.message}")
            }

            override fun onAdLoaded(bannerView: BannerView?) {}
            override fun onAdClicked(bannerView: BannerView?) {}
            override fun onAdDisplayed(bannerView: BannerView?) {}
            override fun onAdClosed(bannerView: BannerView?) {
                Log.e("InAppDisplayBanner", "Ad closed")
            }
        })
        adView?.setAutoRefreshDelay(35)
        adView?.loadAd()
    }


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

}
