package com.apps.quicksketchtrace.activity

import MainViewModel
import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.graphics.drawable.toDrawable
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
import com.apps.quicksketchtrace.databinding.DialogToStartBinding
import com.apps.quicksketchtrace.util.OpenConvert

class ImageDialogFragment : DialogFragment() {
    private var _binding: DialogToStartBinding? = null
    private val binding get() = _binding!!
    private var path = ""
    private lateinit var mainViewModel:MainViewModel

    companion object {
        private const val PIC_KEY = "path"
        fun newInstance(imagePath: String): ImageDialogFragment {
            val args = Bundle().apply {
                putString(PIC_KEY, imagePath)
            }
            return ImageDialogFragment().apply { arguments = args }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = DialogToStartBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        path = arguments?.getString(PIC_KEY) ?: ""
        val bitmap = OpenConvert.loadBitmapFromAssets(requireContext(), path)
        binding.image.setImageBitmap(bitmap)
        binding.imgBack.setOnClickListener { dismiss() }
        mainViewModel = ViewModelProvider(requireActivity())[MainViewModel::class.java]
        mainViewModel.checkIsLocal(path)
        mainViewModel.isLocal.observe(viewLifecycleOwner) { b ->
            if (b != null) {
                binding.imgLike.isSelected=b
            }
        }
        binding.imgLike.setOnClickListener { v ->
            val selected = v.isSelected
            binding.imgLike.isSelected = !selected
            if (!selected) {
                mainViewModel.addLocal(path)
            } else {
                mainViewModel.deleteLocalPath(path)
            }
        }
        binding.rlBtn.setOnClickListener {
            val intent = Intent(requireActivity(), StartDrawActivity::class.java)
            intent.putExtra(StartDrawActivity.PATH_KEY,path)
            startActivity(intent)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    // 设置弹窗居中、透明背景
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState)
        dialog.window?.setBackgroundDrawable(Color.TRANSPARENT.toDrawable())
        return dialog
    }
}