package com.prank.app.color.activity

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.view.View
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.prank.app.color.R
import com.prank.app.color.dbdata.DbTool
import com.prank.app.color.databinding.ActivityImportBinding
import com.prank.app.color.list.AdapterLike
import com.prank.app.color.utils.Common
import com.prank.app.color.utils.ItemDecoration

class ActivityImport : AppCompatActivity(), View.OnClickListener {
    private lateinit var binding: ActivityImportBinding

    private var adapter: AdapterLike? = null
    private var requestRecordAudioLauncher: ActivityResultLauncher<String>? = null
    private var audioPickerLauncher: ActivityResultLauncher<String>? = null
    private var requestStorePermissionsLauncher: ActivityResultLauncher<Array<String>>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityImportBinding.inflate(layoutInflater)
        setContentView(binding.root)
        Common.setStatusBarTextColor(this, true)


        requestRecordAudioLauncher = registerForActivityResult<String, Boolean>(
            ActivityResultContracts.RequestPermission()
        ) { isGranted: Boolean ->
            if (isGranted) {
                intentRecordAudio()
            } else {
                Toast.makeText(
                    this,
                    "Recording permission denied",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
        requestStorePermissionsLauncher = registerForActivityResult(
            ActivityResultContracts.RequestMultiplePermissions()
        ) { result: Map<String, Boolean> ->
            val isGranted = result.all { it.value }

            if (isGranted) {
                importAudio()
            } else {
                Toast.makeText(this, getString(R.string.permission_fail), Toast.LENGTH_SHORT).show()
            }
        }
        audioPickerLauncher = registerForActivityResult(
            ActivityResultContracts.GetContent()
        ) { uri: Uri? ->
            // Handle the returned Uri
            uri?.let {
                val duration = Common.getAudioDuration(this, it)
                val intent = Intent(this, ActivitySave::class.java).apply {
                    putExtra(ActivitySave.KEY_Path, it.toString())
                    putExtra(ActivitySave.KEY_Time, duration)
                }
                startActivity(intent)
            }
        }

        initList()

        binding.btnimport.setOnClickListener(this)
        binding.record.setOnClickListener(this)
        binding.back.setOnClickListener(this)
    }

    private fun initList() {
        val itemHelper = ItemDecoration(5, 5, 0)
        binding.recyclerImport.addItemDecoration(itemHelper)
        binding.recyclerImport.layoutManager = GridLayoutManager(this, 3)
        val all = DbTool.getAllCustomization()

        adapter =
            AdapterLike(this, all, true)
        binding.recyclerImport.adapter = adapter

    }


    private fun checkAndRequestAudioPermission() {
        if (ContextCompat.checkSelfPermission(this, Common.permission_record_audio)
            != PackageManager.PERMISSION_GRANTED
        ) {
            requestRecordAudioLauncher!!.launch(Common.permission_record_audio)
        } else {
            intentRecordAudio()
        }
    }

    private fun intentRecordAudio() {
        val intent = Intent(this, ActivityRecord::class.java)
        startActivity(intent)
    }

    private fun importAudio() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "audio/*"
        audioPickerLauncher!!.launch("audio/*")
    }

    override fun onClick(v: View?) {
        if (v == binding.btnimport) {
            onClickTimer(0)
        } else if (v == binding.record) {
            onClickTimer(1)
        } else if (v == binding.back) {
            finish()
        }
    }

    override fun onResume() {
        super.onResume()
        refresh()
    }

    private fun refresh() {
        if (adapter != null) {
            val all = DbTool.getAllCustomization()
            adapter!!.updateData(all)
        }
    }
    private fun onClickTimer(type: Int) {
        when (type) {
            0 -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                if (ContextCompat.checkSelfPermission(
                        this,
                        Common.permission_read_audio[0]
                    )
                    != PackageManager.PERMISSION_GRANTED
                ) {
                    requestStorePermissionsLauncher!!.launch(Common.permission_read_audio)

                } else {
                    importAudio()
                }
            } else {
                if (ContextCompat.checkSelfPermission(
                        this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                    )
                    != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(
                        this,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                    )
                    != PackageManager.PERMISSION_GRANTED
                ) {
                    requestStorePermissionsLauncher!!.launch(Common.permission_store)

                } else {
                    importAudio()
                }
            }

            1 -> checkAndRequestAudioPermission()
        }
    }
}