package com.design.wallpapergallery.view

import android.app.WallpaperManager
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.ad.tradpluslibrary.TPAdManager
import com.ad.tradpluslibrary.TPAdManager.showTPAD
import com.design.wallpapergallery.R
import com.design.wallpapergallery.data.MainViewModel
import com.design.wallpapergallery.data.Photo
import com.design.wallpapergallery.databinding.ActivityPhotoDownApplyBinding
import com.design.wallpapergallery.listener.OpenTypeListener
import com.design.wallpapergallery.util.DownPicUtils
import com.design.wallpapergallery.util.ChangeTypeUtil
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.request.RequestOptions
import okhttp3.Call
import java.io.File
import java.io.FileInputStream
import java.io.InputStream

class StartDownApplyActivity : AppCompatActivity(), OpenTypeListener {
    companion object {
        var paperKey = "paper"
    }

    private lateinit var binding: ActivityPhotoDownApplyBinding
    lateinit var paper: Photo
    private lateinit var viewModel: MainViewModel
    private var fullUrl = ""
    private var mSavePath = ""
    private lateinit var wallpaperManager: WallpaperManager
    private lateinit var downloadFile: File
    private var call: Call? = null
    private var isGranted = false
    private lateinit var setDialog: SelectDialogFragment
    private var isSetting = false
    private val storagePermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        if (permissions.all { it.value }) {
            isGranted = true
        } else {
            Toast.makeText(this, getString(R.string.no_permit), Toast.LENGTH_SHORT).show()
        }
    }

    private fun requestStoragePermission() {
        val permissions = ChangeTypeUtil.getStoragePermissions()
        if (ChangeTypeUtil.hasStoragePermission(this)) {
            isGranted = true
        } else {
            storagePermissionLauncher.launch(permissions)
        }
    }

    private fun isActivityValid(): Boolean {
        return !isFinishing && !isDestroyed
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPhotoDownApplyBinding.inflate(layoutInflater)
        setContentView(binding.root)
        init()
    }

    override fun onDestroy() {
        super.onDestroy()
        call?.let {
            it.cancel()
        }
        deleteCacheFile()
    }

    private fun init() {
        showTPAD(this) { null }
        viewModel = ViewModelProvider(this)[MainViewModel::class.java]
        paper = intent?.getParcelableExtra(paperKey)!!
        fullUrl = paper.fullUrl
        mSavePath = ChangeTypeUtil.getSaveFilePath(this, paper.imId)
        downloadFile = File(mSavePath)
        setDialog = SelectDialogFragment()
        setDialog.setListener(this@StartDownApplyActivity)
        wallpaperManager = WallpaperManager.getInstance(this)
        Glide.with(this)
            .load(paper.previewUrl1080)
            .apply(
                RequestOptions()
                    .format(DecodeFormat.PREFER_RGB_565)
            )
            .skipMemoryCache(true)
            .thumbnail(
                Glide.with(this)
                    .load(paper.previewUrl400)
                    .apply(
                        RequestOptions()
                            .format(DecodeFormat.PREFER_RGB_565)
                            .centerCrop()
                    )
            )
            .into(binding.image)
        binding.imageBack.setOnClickListener { showTPAD(this) { finish() } }
        binding.tvContent.text = paper.description
        viewModel.isLiked.observe(this) { b ->
            Log.d("initb", b.toString())
            if (b != null) {
                binding.imageLike.isSelected = b
            }
        }
        viewModel.checkLike(paper.imId)
        binding.imageLike.setOnClickListener {
            setLikeStatus()
        }

        binding.layoutDownload.setOnClickListener {
            startDownload()
        }
        binding.layoutSet.setOnClickListener {
            showSetDialog()
        }
    }

    private fun showSetDialog() {
        if (isSetting) return
        if (!setDialog.isAdded) {
            setDialog.show(supportFragmentManager, "")
        }
    }

    private fun setLikeStatus() {
        val b = !binding.imageLike.isSelected
        binding.imageLike.isSelected = !b
        paper.isLike = !b
        viewModel.setLike(paper)
    }

    private fun startDownload() {
        requestStoragePermission()
        if (!isGranted) return
        showDownloadLoading(true)
        if (downloadFile.exists()) {
            saveToGallery()
            return
        }
        doDownload()
    }

    private fun saveToGallery() {
        val uri: Uri? = DownPicUtils.saveToGallery(this, downloadFile)
        if (!isActivityValid()) return
        runOnUiThread {
            showDownloadLoading(false)
            if (uri == null) {
                Toast.makeText(
                    this@StartDownApplyActivity,
                    getString(R.string.save_fail),
                    Toast.LENGTH_SHORT
                ).show()
            } else {
                Toast.makeText(
                    this@StartDownApplyActivity,
                    getString(R.string.save_success),
                    Toast.LENGTH_SHORT
                ).show()
            }
            Log.d("YYYYYY", "--------path=" + downloadFile.getAbsolutePath() + "---uri=" + uri)
        }
    }

    private fun doDownload() {
        call = DownPicUtils.downloadFile(fullUrl, mSavePath, object : DownPicUtils.ConnectCallBack {
            override fun onResult(success: Boolean, inputStream: InputStream?) {
                val file = File(mSavePath)
                if (file.exists() && success) {
                    downloadFile = file
                    saveToGallery()
                } else {
                    if (!isActivityValid()) return
                    runOnUiThread {
                        showDownloadLoading(false)
                        Toast.makeText(
                            this@StartDownApplyActivity,
                            getString(R.string.down_fail),
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            }

        })
    }

    private fun showDownloadLoading(show: Boolean) {
        if (show) {
            binding.pbDownload.visibility = View.VISIBLE
            binding.imageDownload.visibility = View.GONE
        } else {
            binding.pbDownload.visibility = View.GONE
            binding.imageDownload.visibility = View.VISIBLE
        }
    }

    private fun deleteCacheFile() {
        if (downloadFile.exists()) {
            val delete = downloadFile.delete()
            Log.d("YYYYYY", "--------delete=$delete")
        }
    }

    override fun onClick(type: Int) {
        showSetWallpaperLoading(true)
        if (downloadFile.exists()) {
            Thread {
                Log.d("YYYYYY", "skip download and set")
                setWallPaper(downloadFile, type)
            }.start()
        } else {
            call =
                DownPicUtils.downloadFile(
                    fullUrl,
                    mSavePath,
                    object : DownPicUtils.ConnectCallBack {
                        override fun onResult(success: Boolean, inputStream: InputStream?) {
                            val file = File(mSavePath)
                            if (file.exists() && success) {
                                downloadFile = file
                                setWallPaper(downloadFile, type)
                            } else {
                                showDownloadLoading(false)
                                runOnUiThread {
                                    Toast.makeText(
                                        this@StartDownApplyActivity,
                                        getString(R.string.set_fail),
                                        Toast.LENGTH_SHORT
                                    ).show()
                                }
                            }
                        }

                    })
        }
    }

    private fun showSetWallpaperLoading(show: Boolean) {
        Log.d("YYYYYY", "-----------showSetWallpaperLoading$show")
        if (show) {
            isSetting = true
            binding.pbSet.visibility = View.VISIBLE
            binding.txApply.visibility = View.GONE
        } else {
            isSetting = false
            binding.pbSet.visibility = View.GONE
            binding.txApply.visibility = View.VISIBLE
        }
    }

    private fun setWallPaper(file: File, type: Int) {
        try {
            FileInputStream(file).use { fileInputStream ->
                when (type) {
                    SelectDialogFragment.TYPE_HOME -> {
                        // FLAG_SYSTEM 表示设置为主屏幕壁纸
                        wallpaperManager.setStream(
                            fileInputStream,
                            null,
                            true,
                            WallpaperManager.FLAG_SYSTEM
                        )
                    }

                    SelectDialogFragment.TYPE_LOCK -> {
                        // FLAG_LOCK 设置为锁屏壁纸
                        wallpaperManager.setStream(
                            fileInputStream,
                            null,
                            true,
                            WallpaperManager.FLAG_LOCK
                        )
                    }

                    SelectDialogFragment.TYPE_BOTH -> {
                        // 同时设置主屏和锁屏壁纸
                        wallpaperManager.setStream(fileInputStream)
                    }

                    else -> {}
                }
            }
            if (!isActivityValid()) return
            runOnUiThread {
                showSetWallpaperLoading(false)
                Toast.makeText(
                    this@StartDownApplyActivity,
                    getString(R.string.set_success),
                    Toast.LENGTH_SHORT
                ).show()
            }
        } catch (e: Exception) {
            if (!isActivityValid()) return
            runOnUiThread {
                showSetWallpaperLoading(false)
                Toast.makeText(
                    this@StartDownApplyActivity,
                    getString(R.string.set_fail),
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }
}