package com.adpro.pixelshow.look

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.maxlibrary.MaxManager
import com.adpro.pixelshow.R
import com.adpro.pixelshow.data.MainViewModel
import com.adpro.pixelshow.data.Movie
import com.adpro.pixelshow.databinding.ActivityDownRequestBinding
import com.adpro.pixelshow.event.IntentListener
import com.adpro.pixelshow.util.ApplyUtils
import com.adpro.pixelshow.util.TypeUtil
import com.adpro.pixelshow.util.TopBarUtils
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 DownloadRequestActivity : AppCompatActivity(), IntentListener {
    companion object {
        var paperKey = "paper"
    }

    private lateinit var binding: ActivityDownRequestBinding
    lateinit var paper: Movie
    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: ToApplyDialog
    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 = TypeUtil.getStoragePermissions()
        if (TypeUtil.hasStoragePermission(this)) {
            isGranted = true
        } else {
            storagePermissionLauncher.launch(permissions)
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityDownRequestBinding.inflate(layoutInflater)
        setContentView(binding.root)
        TopBarUtils.setStatusBar(this.window)
        TopBarUtils.setLightStatusBar(this.window,true)
        MaxManager.onLoadAd()
        MaxManager.startShowMaxAd (this){}
        init()
    }
    override fun onDestroy() {
        super.onDestroy()
        call?.let {
            it.cancel()
        }
        deleteCacheFile()
    }
    private fun isActivityValid(): Boolean {
        return !isFinishing && !isDestroyed
    }
    private fun init() {
        viewModel = ViewModelProvider(this)[MainViewModel::class.java]
        paper = intent?.getParcelableExtra(paperKey)!!
        fullUrl = paper.fullUrl
        mSavePath = TypeUtil.getSaveFilePath(this, paper.imId)
        downloadFile = File(mSavePath)
        setDialog = ToApplyDialog()
        setDialog.setListener(this@DownloadRequestActivity)
        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 {
            MaxManager.startShowMaxAd (this){
                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? = ApplyUtils.saveToGallery(this, downloadFile)
        if (!isActivityValid()) return
        runOnUiThread {
            showDownloadLoading(false)
            if (uri == null) {
                Toast.makeText(
                    this@DownloadRequestActivity,
                    getString(R.string.save_fail),
                    Toast.LENGTH_SHORT
                ).show()
            } else {
                Toast.makeText(
                    this@DownloadRequestActivity,
                    getString(R.string.save_success),
                    Toast.LENGTH_SHORT
                ).show()
            }
            Log.d("YYYYYY", "--------path=" + downloadFile.getAbsolutePath() + "---uri=" + uri)
        }
    }

    private fun doDownload() {
        call = ApplyUtils.downloadFile(fullUrl, mSavePath, object : ApplyUtils.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@DownloadRequestActivity,
                            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 =
                ApplyUtils.downloadFile(fullUrl, mSavePath, object : ApplyUtils.ConnectCallBack {
                    override fun onResult(success: Boolean, inputStream: InputStream?) {
                        val file = File(mSavePath)
                        if (file.exists() && success) {
                            downloadFile = file
                            setWallPaper(downloadFile, type)
                        } else {
                            showDownloadLoading(false)
                            if (!isActivityValid()) return
                            runOnUiThread {
                                Toast.makeText(
                                    this@DownloadRequestActivity,
                                    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 setWallPaper(file: File, type: Int) {
        try {
            FileInputStream(file).use { fileInputStream ->
                when (type) {
                    ToApplyDialog.TYPE_HOME -> {
                        // FLAG_SYSTEM 表示设置为主屏幕壁纸
                        wallpaperManager.setStream(
                            fileInputStream,
                            null,
                            true,
                            WallpaperManager.FLAG_SYSTEM
                        )
                    }

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

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

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