package com.wall.photography.wallpaper.activivty


import android.app.WallpaperManager
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.isVisible
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.wall.photography.wallpaper.MyApp
import com.wall.photography.wallpaper.R
import com.wall.photography.wallpaper.util.Utils
import com.wall.photography.wallpaper.data.Bean
import com.wall.photography.wallpaper.databinding.ActivitySetWallpaperBinding
import com.wall.photography.wallpaper.manager.DealData
import com.wall.photography.wallpaper.manager.Other
import com.wall.photography.wallpaper.room.MyDataBase
import com.wall.photography.wallpaper.topon.AdManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File


class SetWallpaperActivity : AppCompatActivity(), View.OnClickListener {

    companion object {
        const val KEY_DATA = "key_data"
        const val KEY_MAIN_ENTER = "key_main_enter"
    }

    private var code = 1

    private var dialog: SelectDialog? = null

    private lateinit var wallpaperManager: WallpaperManager

    private lateinit var data: Bean
    private lateinit var vb: ActivitySetWallpaperBinding

    private var mainEnter = true
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d(MyApp.TAG, "----------SetWallpaperActivity--onCreate=$this")
        AdManager.loadAllAd()
        vb = ActivitySetWallpaperBinding.inflate(layoutInflater)
        setContentView(vb.root)
        vb.loadingView.isVisible = true
        initBar()
        data = intent.getSerializableExtra(KEY_DATA) as Bean
        mainEnter = intent.getBooleanExtra(KEY_MAIN_ENTER, true)

        wallpaperManager = WallpaperManager.getInstance(this)
        CoroutineScope(Dispatchers.IO).launch {
            data = MyDataBase.getInstance().getBeanDao().getCurWallpaper(data.id)
            vb.imLove.isSelected = data.love
            data.downloadFilePath?.let {
                val file = File(it)
                if (file.exists()) {
                    withContext(Dispatchers.Main) {
                        Log.d(MyApp.TAG, "-------------load file =${it}")
                        Glide.with(MyApp.application)
                            .asDrawable()
                            .load(file)
                            .skipMemoryCache(true)
                            .thumbnail(0.2f)
                            .error(R.drawable.placeholder)
                            .placeholder(R.drawable.placeholder)
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .into(vb.preview)
                    }
                }

            }
        }
        initView()
        setClick()
        relayout()
    }


    private fun relayout() {
        val navigationBarHeight = Other.getNavigationBarHeight(MyApp.application)
        Log.d(MyApp.TAG, "-------navigationBarHeight=${navigationBarHeight}")

        if (navigationBarHeight != 0) {
            val newLayoutParams = vb.relayout.layoutParams as ConstraintLayout.LayoutParams
            vb.relayout.layoutParams = newLayoutParams.apply {
                bottomMargin = navigationBarHeight + Other.dpToPx(20, MyApp.application)
            }
        }


    }

    private fun setClick() {
        vb.run {
            back.setOnClickListener(this@SetWallpaperActivity)
            imDownload.setOnClickListener(this@SetWallpaperActivity)
            imSetWallpaper.setOnClickListener(this@SetWallpaperActivity)
            imLove.setOnClickListener(this@SetWallpaperActivity)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == code) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startSaveIm()
            } else {
                Toast.makeText(this, getString(R.string.grant_permission), Toast.LENGTH_SHORT)
                    .show()
            }
        }
    }


    private fun startSaveIm() {
        vb.loadingView.isVisible = true
        data.downloadFilePath?.let { path ->
            Log.d(MyApp.TAG, "-------------has downloadFilePath  =${path}")
            val file = File(path)
            if (file.exists()) {
                val saveToGallery = DealData.saveToGallery(this@SetWallpaperActivity, file)
                Log.d(MyApp.TAG, "------------file exist")
                saveResultToast(
                    if (saveToGallery != null) getString(R.string.save_ok) else getString(
                        R.string.save_fail
                    )
                )
            } else {
                Log.d(MyApp.TAG, "-------------file no exist")
                downloadIm {
                    var msg: String = if (it == null) {
                        getString(R.string.save_exception)
                    } else {
                        val newFile = File(it)
                        val saveToGallery =
                            DealData.saveToGallery(this@SetWallpaperActivity, newFile)
                        if (saveToGallery != null) getString(R.string.save_ok) else getString(
                            R.string.save_fail
                        )
                    }
                    saveResultToast(msg)
                }
            }
        } ?: run {
            downloadIm {
                var msg: String = if (it == null) {
                    getString(R.string.save_exception)
                } else {
                    val newFile = File(it)
//                    val saveToGallery = DealData.saveToGallery(this@SetWallpaperActivity, newFile)
                    val saveToGallery = Utils.saveToGallery(this@SetWallpaperActivity, newFile)
                    if (saveToGallery != null) getString(R.string.save_ok) else getString(
                        R.string.save_fail
                    )
                }
                saveResultToast(msg)
            }
        }
    }

    private fun saveResultToast(message: String) {
        runOnUiThread {
            Toast.makeText(
                this@SetWallpaperActivity,
                message,
                Toast.LENGTH_SHORT
            ).show()

            vb.loadingView.isVisible = false
        }
    }

    private fun downloadIm(result: (filePath: String?) -> Unit) {
        val filePath = Other.getInternalFilePath(this)
        Log.d(MyApp.TAG, "-------------start  downloadIm =${filePath}")
        DealData.downloadFile(data.download, filePath) { isSave, inputStream ->
            val file = File(filePath)
            if (!isSave || inputStream == null || !file.exists()) {
                Log.d(MyApp.TAG, "-------------downloadIm  fail")
                result.invoke(null)
                return@downloadFile
            }
            MyDataBase.getInstance().getBeanDao().updateBean(data.apply {
                downloadFilePath = filePath
            })
            result.invoke(filePath)
            Log.d(
                MyApp.TAG,
                "-------------updateBean=${data.id}  ${data.downloadFilePath} thread=${Thread.currentThread().name}"
            )
        }
    }

    private fun initView() {
        vb.run {
            data.run {
                authorName.text = user.name
                Log.d(MyApp.TAG, "-------------load reguar initView")
                loadRegular()
                Glide.with(MyApp.application)
                    .asDrawable()
                    .load(user.header_medium)
                    .thumbnail(0.2f)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .error(R.drawable.placeholder)
                    .placeholder(R.drawable.placeholder)
                    .listener(object : RequestListener<Drawable> {
                        override fun onLoadFailed(
                            e: GlideException?,
                            model: Any?,
                            target: Target<Drawable>,
                            isFirstResource: Boolean
                        ): Boolean {
                            vb.loadingView.isVisible = false
                            return false
                        }

                        override fun onResourceReady(
                            resource: Drawable,
                            model: Any,
                            target: Target<Drawable>?,
                            dataSource: DataSource,
                            isFirstResource: Boolean
                        ): Boolean {
                            vb.loadingView.isVisible = false
                            return false
                        }

                    })
                    .into(header)
            }
        }

    }

    private fun loadRegular() {
        Glide.with(MyApp.application)
            .asDrawable()
            .load(data.urls.regular)
            .thumbnail(0.2f)
            .error(R.drawable.placeholder)
            .skipMemoryCache(true)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .placeholder(R.drawable.placeholder)
            .into(vb.preview)

    }


    private fun initBar() {
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        vb.root.systemUiVisibility =
            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
    }

    override fun onPause() {
        super.onPause()
        Log.d(MyApp.TAG, "-------------onPause")
        CoroutineScope(Dispatchers.IO).launch {
            vb.imLove.isSelected.let {
                MyDataBase.getInstance().getBeanDao().updateBean(data.apply {
                    love = it
                })

            }
        }

    }

    override fun onBackPressed() {
        super.onBackPressed()
        AdManager.showTopOn(this@SetWallpaperActivity) {
        }

    }

    override fun onClick(v: View?) {
        v?.run {
            vb.run {
                when (v) {
                    back -> {
                        AdManager.showTopOn(this@SetWallpaperActivity) {
                            finish()
                        }

                    }

                    imLove -> {
                        AdManager.showTopOn(this@SetWallpaperActivity) {
                            imLove.isSelected = !imLove.isSelected

                            var msg: String = if (imLove.isSelected) {
                                getString(R.string.like_success)
                            } else {
                                getString(R.string.cancel_like_success)
                            }
                            Toast.makeText(this@SetWallpaperActivity, msg, Toast.LENGTH_SHORT)
                                .show()
                        }

                    }

                    imSetWallpaper -> {
                        if (dialog == null) {
                            dialog = SelectDialog {
                                vb.loadingView.visibility = View.VISIBLE
                                Log.d(
                                    MyApp.TAG,
                                    "-------------isVisible ${Thread.currentThread().name}"
                                )
                                data.downloadFilePath?.let { filePath ->
                                    val file = File(filePath)
                                    if (file.exists()) {
                                        launchSet(it, file)
                                    } else {
                                        downloadIm { downloadpath ->
                                            if (downloadpath == null) {
                                                saveResultToast(getString(R.string.download_exception))
                                            } else {
                                                val file1 = File(downloadpath)
                                                launchSet(it, file1)
                                            }
                                        }
                                    }
                                } ?: run {
                                    downloadIm { downloadpath ->
                                        if (downloadpath == null) {
                                            saveResultToast(getString(R.string.download_exception))
                                        } else {
                                            val file1 = File(downloadpath)
                                            launchSet(it, file1)
                                        }
                                    }
                                }

                            }
                        }
                        if (!isFinishing) {
                            dialog?.show(supportFragmentManager, "")
                        }
                    }

                    imDownload -> {
                        AdManager.showTopOn(this@SetWallpaperActivity) {
                            if (Other.requestPermission(this@SetWallpaperActivity, code)) {
                                startSaveIm()
                            }
                        }
                    }

                    else -> {}
                }


            }
        }

    }

    private fun launchSet(type: Int, file: File) {
        CoroutineScope(Dispatchers.Main).launch {

            AdManager.showTopOn(
                this@SetWallpaperActivity
            ) {
                var msg: String = try {
                    startSetWallpaper(type, file)
                    getString(R.string.set_success)
                } catch (ex: Exception) {
                    getString(R.string.set_fail)
                }
                saveResultToast(msg)
                Log.d(MyApp.TAG, "------------end SetWallpaper")
            }


        }
    }

    private fun startSetWallpaper(type: Int, file: File) {
        Log.d(MyApp.TAG, "------------start SetWallpaper")

        when (type) {
            SelectDialog.clickType_home -> {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                    wallpaperManager.setStream(file.inputStream())
                } else {
                    wallpaperManager.setStream(
                        file.inputStream(),
                        null,
                        true,
                        WallpaperManager.FLAG_SYSTEM
                    )
                }
            }

            SelectDialog.clickType_lock -> {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                    wallpaperManager.setStream(file.inputStream())
                } else {
                    wallpaperManager.setStream(
                        file.inputStream(),
                        null,
                        true,
                        WallpaperManager.FLAG_LOCK
                    )
                }
            }

            SelectDialog.clickType_both -> {
                wallpaperManager.setStream(file.inputStream())
            }
        }


    }

    override fun onDestroy() {
        super.onDestroy()
        dialog?.dismiss()
        Glide.with(MyApp.application).clear(vb.preview)
    }
}