package com.quiescent.wallpaper.collection.test.ui

import android.app.WallpaperManager
import android.graphics.BitmapFactory
import android.os.Build
import android.widget.Toast
import androidx.core.view.isVisible
import com.applovin.mediation.ads.MaxInterstitialAd
import com.quiescent.wallpaper.collection.test.R
import com.quiescent.wallpaper.collection.test.bean.InfoList
import com.quiescent.wallpaper.collection.test.databinding.ActivitySetWactivityBinding
import com.quiescent.wallpaper.collection.test.tool.Utils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.quiescent.wallpaper.collection.test.InterstitialManager
import com.quiescent.wallpaper.collection.test.InterstitialManager.setMyCallBack
import java.io.File

class ActivitySetWallpaper : BaseActivity<ActivitySetWactivityBinding>() {

    companion object {
        val KEY_DATA = "key_data"
    }

    private var data: InfoList? = null

    private lateinit var wallMan: WallpaperManager


    private lateinit var myFilePath: String

    private var sourceFile: File? = null

    private lateinit var adList: List<MaxInterstitialAd>
    override fun getViewBinding(): ActivitySetWactivityBinding {
        return ActivitySetWactivityBinding.inflate(layoutInflater)
    }

    override fun onViewUi() {
        adList = InterstitialManager.startLoadAd(this@ActivitySetWallpaper)
        data = intent.getSerializableExtra(KEY_DATA) as InfoList
        wallMan = WallpaperManager.getInstance(this)
        myFilePath = "${applicationContext.cacheDir.path}/${data!!.source.substringAfterLast("/")}"
        display()
        onClick()


    }

    override fun onBackPressed() {
        super.onBackPressed()
        startShowAd {

        }
    }


    private fun startShowAd(action: () -> Unit) {
        val readyAd = InterstitialManager.getReadyAd(adList)
        if (readyAd != null) {
            readyAd.setMyCallBack(object : InterstitialManager.MyCallBack {
                override fun adShowFail() {
                    action.invoke()
                }

                override fun adShowHidden() {
                    action.invoke()
                }

            })
            readyAd.showAd()

        } else {
            action.invoke()
        }
    }

    private fun display() {
        data?.source.let {
            setLoading(true)
            Glide.with(this).downloadOnly().load(it)
                .addListener(object : RequestListener<File> {
                    override fun onLoadFailed(
                        e: GlideException?,
                        model: Any?,
                        target: Target<File>,
                        isFirstResource: Boolean
                    ): Boolean {
                        setLoading(false)
                        sourceFile = null
                        Toast.makeText(
                            this@ActivitySetWallpaper,
                            getString(R.string.download_fail),
                            Toast.LENGTH_SHORT
                        ).show()
                        return false
                    }

                    override fun onResourceReady(
                        resource: File,
                        model: Any,
                        target: Target<File>?,
                        dataSource: DataSource,
                        isFirstResource: Boolean
                    ): Boolean {
                        setLoading(false)
                        binding.wallpaperIm.setImageBitmap(BitmapFactory.decodeFile(resource.absolutePath))
                        sourceFile = resource
                        return false
                    }

                }).preload()

        }

    }

    private fun onClick() {
        binding.backIm.setOnClickListener {
            startShowAd {
                finish()
            }

        }

        binding.setBtnTv.setOnClickListener {
            setLoading(true)
            if (data != null) {
                startShowAd {
                    if (File(myFilePath).exists()) {
                        setMyWallpaper(File(myFilePath))
                        setLoading(false)
                    } else {
                        fileDownload()
                    }
                }
            } else {
                setLoading(false)
            }


        }
    }

    private fun setMyWallpaper(file: File) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            wallMan.setStream(
                file.inputStream(),
                null,
                true,
                WallpaperManager.FLAG_SYSTEM
            )
        } else {
            wallMan.setStream(file.inputStream())
        }
        finish()
        Toast.makeText(
            this@ActivitySetWallpaper,
            getString(R.string.set_success),
            Toast.LENGTH_SHORT
        )
            .show()
    }

    private fun setLoading(isLoading: Boolean) {
        binding.loading.isVisible = isLoading
        binding.setBtnTv.isEnabled = !isLoading
    }

    private fun fileDownload() {
        if (sourceFile == null) {
            display()
        } else {
            sourceFile?.let {
                val copyFile = Utils.fileToCache(it.absolutePath, myFilePath)
                if (copyFile) {
                    setMyWallpaper(File(myFilePath))
                }
                setLoading(false)
            }
        }


    }


}