package com.paperapp.lenscape.preview

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.paperapp.lenscape.R
import com.paperapp.lenscape.element.MainViewModel
import com.paperapp.lenscape.element.Element
import com.paperapp.lenscape.tools.OnclickListener
import com.paperapp.lenscape.tools.SetWayUtils
import com.paperapp.lenscape.tools.ImagePreUtil
import com.paperapp.lenscape.TopBarUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.request.RequestOptions
import com.paperapp.lenscape.databinding.ActivityImagePreviewBinding
import okhttp3.Call
import java.io.File
import java.io.FileInputStream
import java.io.InputStream

class ImagePreviewActivity : AppCompatActivity(), OnclickListener {
    companion object {
        var paperKey = "wallpaperData"
    }

    private lateinit var binding: ActivityImagePreviewBinding
    lateinit var paper: Element
    private lateinit var viewModel: MainViewModel
    private var fullImageUrl = ""
    private var fileSavePath = ""
    private lateinit var wallpaperManager: WallpaperManager
    private lateinit var downloadedFile: File
    private var call: Call?=null
    private var isGranted = false
    private lateinit var setDialog: GuideDialog
    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 isActivityAlive(): Boolean {
        return !isFinishing && !isDestroyed
    }
    private fun requestStoragePermission() {
        val permissions = ImagePreUtil.getStoragePermissions()
        if (ImagePreUtil.hasStoragePermission(this)) {
            isGranted = true
        } else {
            storagePermissionLauncher.launch(permissions)
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityImagePreviewBinding.inflate(layoutInflater)
        setContentView(binding.root)
        TopBarUtils.setStatusBar(this.window)
        TopBarUtils.setLightStatusBar(this.window,true)
        initializeComponents()
    }
    override fun onDestroy() {
        super.onDestroy()
        call?.let {
            it.cancel()
        }
        deleteCacheFile()
    }

    private fun initializeComponents() {
        viewModel = ViewModelProvider(this)[MainViewModel::class.java]
        paper = intent?.getParcelableExtra(paperKey)!!
        fullImageUrl = paper.fullUrl
        fileSavePath = ImagePreUtil.getSaveFilePath(this, paper.imId)
        downloadedFile = File(fileSavePath)
        setDialog = GuideDialog()
        setDialog.setListener(this@ImagePreviewActivity)
        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 { 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 {
            initiateDownload()
        }
        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 initiateDownload() {
        requestStoragePermission()
        if (!isGranted) return
        showDownloadLoading(true)
        if (downloadedFile.exists()) {
            saveToGallery()
            return
        }
        downloadImageFile()
    }

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

    private fun downloadImageFile() {
        call = SetWayUtils.downloadFile(fullImageUrl, fileSavePath, object : SetWayUtils.ConnectCallBack {
            override fun onResult(success: Boolean, inputStream: InputStream?) {
                val file = File(fileSavePath)
                if (file.exists() && success) {
                    downloadedFile = file
                    saveToGallery()
                } else {
                    if(!isActivityAlive()) return
                    runOnUiThread {
                        showDownloadLoading(false)
                        Toast.makeText(
                            this@ImagePreviewActivity,
                            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 (downloadedFile.exists()) {
            val delete = downloadedFile.delete()
            Log.d("YYYYYY", "--------delete=$delete")
        }
    }

    override fun onClick(type: Int) {
        showSetWallpaperLoading(true)
        if (downloadedFile.exists()) {
            Thread {
                Log.d("YYYYYY", "skip download and set")
                setWallpaperFromFile(downloadedFile, type)
            }.start()
        } else {
            call =
                SetWayUtils.downloadFile(fullImageUrl, fileSavePath, object : SetWayUtils.ConnectCallBack {
                    override fun onResult(success: Boolean, inputStream: InputStream?) {
                        val file = File(fileSavePath)
                        if (file.exists() && success) {
                            downloadedFile = file
                            setWallpaperFromFile(downloadedFile, type)
                        } else {
                            if(!isActivityAlive()) return
                            showDownloadLoading(false)
                            runOnUiThread {
                                Toast.makeText(
                                    this@ImagePreviewActivity,
                                    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
        } else {
            isSetting = false
            binding.pbSet.visibility = View.GONE
        }
    }

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

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

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

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