package com.soundapp.soundgags.ui

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts.GetContent
import androidx.activity.result.contract.ActivityResultContracts.RequestMultiplePermissions
import androidx.activity.result.contract.ActivityResultContracts.RequestPermission
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.soundapp.soundgags.R
import com.soundapp.soundgags.databinding.FragmentSoundBinding
import com.soundapp.soundgags.setting.SetUtil
import com.soundapp.soundgags.setting.FavSolidAdapter
import com.soundapp.soundgags.datame.Reflection
import com.soundapp.soundgags.datame.MainViewModel
import com.soundapp.soundgags.setting.LikeUpClickListener

class SoundFragment(viewModel: MainViewModel) : Fragment(),LikeUpClickListener{
    private lateinit var binding: FragmentSoundBinding
    private val mianViewModel: MainViewModel = viewModel
    private lateinit var adapter: FavSolidAdapter
    private var type: Int = 1
    private var permission_read_audio: Array<String> = arrayOf(Manifest.permission.READ_MEDIA_AUDIO)
    private var permission_record_audio: String = Manifest.permission.RECORD_AUDIO
    private var permission_store: Array<String> = arrayOf(
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE
    )
    private lateinit var requestStorePermissionsLauncher: ActivityResultLauncher<Array<String>>
    private lateinit var requestRecordAudioLauncher: ActivityResultLauncher<String>
    private lateinit var audioPickerLauncher: ActivityResultLauncher<String>
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // Inflate the layout for this fragment
        binding = FragmentSoundBinding.inflate(inflater, container, false)
        initView()
        return binding.root
    }

    override fun onResume() {
        super.onResume()
        mianViewModel.loadCustomItems()
        mianViewModel.loadLikeItems()
    }
    private fun initView() {
        adapter = FavSolidAdapter()
        adapter.setListener(this)
        mianViewModel.customItems.observe(viewLifecycleOwner){customList ->
            Log.d("CustomFragment", "initView: $customList")
            if(customList.isEmpty()){
                binding.emptyView.visibility=View.VISIBLE
                binding.recyclerView.visibility=View.GONE
            }else{
                binding.emptyView.visibility=View.GONE
                binding.recyclerView.visibility=View.VISIBLE
                adapter.setList(customList,1)
                Log.d("CustomFragment", "initView: ${adapter.itemCount}")
                adapter.notifyDataSetChanged()
            }
        }
        mianViewModel.likeItems.observe(viewLifecycleOwner) { likeList ->
            Log.d("CustomFragment", "likeItems updated: ${likeList.size}")
            mianViewModel.loadCustomItems()
        }
        binding.recyclerView.adapter = adapter
        binding.recyclerView.layoutManager=
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL,false)
        selectBtnStyle()//初始化默认选择录制按钮
        binding
        binding.recordImg.setOnClickListener {
            type=1
            Log.d("---------", "========type=$type")
            selectBtnStyle()
        }
        binding.diyImg.setOnClickListener {
            type=0
            Log.d("---------", "========type=$type")
            selectBtnStyle()
        }
        binding.upload.setOnClickListener {
            selectBtnClick(type)
        }
        requestRecordAudioLauncher = registerForActivityResult<String, Boolean>(
            RequestPermission()
        ) { isGranted: Boolean ->
            if (isGranted) {
                intentRecordAudio()
            } else {
                Toast.makeText(requireContext(), "Recording permission denied", Toast.LENGTH_SHORT)
                    .show()
            }
        }

        requestStorePermissionsLauncher =
            registerForActivityResult<Array<String>, Map<String, Boolean>>(
                RequestMultiplePermissions()
            ) { result ->
                var isGranted = true
                for ((_, value) in result) {
                    isGranted = value
                    if (!value) {
                        isGranted = false
                    }
                }
                if (isGranted) {
                    importFromLocal()
                } else {
                    Toast.makeText(requireContext(), " permits denied", Toast.LENGTH_SHORT)
                        .show()
                }
            }
        audioPickerLauncher = registerForActivityResult<String, Uri>(
            GetContent()
        ) { uri -> // Handle the returned Uri

            if (uri != null) {
                Log.d("---------", "========uri=$uri")
                val duration: Long = SetUtil.getAudioDuration(requireContext(), uri)
                val intent = Intent(
                    requireContext(),
                    VoiceRecorderActivity::class.java
                )
                intent.putExtra(VoiceRecorderActivity.KEY_Path, uri.toString())
                intent.putExtra(VoiceRecorderActivity.KEY_Time, duration)
                startActivity(intent)
            }
        }
    }

    private fun selectBtnStyle() {
        if(type == 0){
            binding.recordImg.background=requireContext().getDrawable(R.drawable.record_tran_alittile)
            binding.diyImg.background=requireContext().getDrawable(R.drawable.gradient_sel_back)
            binding.upload.text= requireActivity().getString(R.string.start_upload)

        }else{
            binding.recordImg.background=requireContext().getDrawable(R.drawable.gradient_sel_back)
            binding.diyImg.background=requireContext().getDrawable(R.drawable.record_tran_alittile)
            binding.upload.text= requireActivity().getString(R.string.start_record)
        }
    }
    override fun onMoreClick(reflection: Reflection,isAdd: Boolean) {
        mianViewModel.updateLikeStatus(reflection.name,!isAdd)
    }

    override fun onCustomizationClick(reflection: Reflection) {
        mianViewModel.deleteItem(reflection)
    }
    fun selectBtnClick(type: Int) {
        if(type == 0){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                if (ContextCompat.checkSelfPermission(
                        requireContext(),
                        permission_read_audio[0]
                    )
                    != PackageManager.PERMISSION_GRANTED
                ) {
                    requestStorePermissionsLauncher.launch(permission_read_audio)
                    //                    ActivityCompat.requestPermissions(requireActivity(), ConstValues.permission_read_audio,
//                            ConstValues.REQUEST_READ_STORAGE_PERMISSION);
                } else {
                    importFromLocal()
                }
            } else {
                if ((ContextCompat.checkSelfPermission(
                        requireContext(),
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                    )
                            != PackageManager.PERMISSION_GRANTED) ||
                    (ContextCompat.checkSelfPermission(
                        requireContext(),
                        Manifest.permission.READ_EXTERNAL_STORAGE
                    )
                            != PackageManager.PERMISSION_GRANTED)
                ) {
                    requestStorePermissionsLauncher.launch(permission_store)
                    //                    ActivityCompat.requestPermissions(requireActivity(), ConstValues.permission_store, ConstValues.REQUEST_READ_STORAGE_PERMISSION);
                } else {
                    importFromLocal()
                }
            }
        }
        else{
            checkAndRequestAudioPermission()
        }
    }
    private fun importFromLocal() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.setType("audio/*")
        audioPickerLauncher.launch("audio/*")
    }
    private fun checkAndRequestAudioPermission() {
        if (ContextCompat.checkSelfPermission(requireContext(), permission_record_audio)
            != PackageManager.PERMISSION_GRANTED
        ) {
            requestRecordAudioLauncher.launch(permission_record_audio)
        } else {
            intentRecordAudio()
        }
    }
    private fun intentRecordAudio() {
        val intent = Intent(requireContext(), LocalMusicActivity::class.java)
        startActivity(intent)
    }
}