package com.various.funny.sounds.audio.helper

import android.content.Context
import android.media.AudioManager
import android.widget.SeekBar
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.various.funny.sounds.audio.VariousFunnySounds
import com.various.funny.sounds.audio.data.NewBean
import com.various.funny.sounds.audio.data.NewBeanChild
import com.various.funny.sounds.audio.db.MyRoomBase
import org.json.JSONArray
import org.json.JSONObject
import java.io.BufferedReader
import java.io.File
import java.io.InputStream
import java.io.InputStreamReader
import java.io.StringWriter

object ComUtils {

    const val DB_Name = "funny sounds"
    const val DB_Version = 1
    const val TABLE_Name_Category = "category"
    const val TABLE_Name_Sounds = "sounds"

    fun getScreenWidthPx(): Int {
        return VariousFunnySounds.appContext.resources.displayMetrics.widthPixels
    }


    fun dpToPx(dpV: Float): Int {
        VariousFunnySounds.appContext.resources.displayMetrics.density.let {
            val value = dpV * it + 0.5f
            return value.toInt()
        }
    }

    fun getFileString(input: InputStream): String {
        val charArray = CharArray(input.available())
        var count = 0
        val stringWriter = StringWriter()
        val inputStreamReader = InputStreamReader(input)
        val bufferedReader = BufferedReader(inputStreamReader)
        while (bufferedReader.read(charArray).also { count = it } != -1) {
            stringWriter.write(charArray, 0, count)
        }
        return stringWriter.toString()
    }

      fun setPlayVolume(context: Context, seekBar: SeekBar) {
        val audioManager = context.getSystemService(AppCompatActivity.AUDIO_SERVICE) as AudioManager
        val maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
        seekBar.max = maxVolume
        seekBar.progress = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0)
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}
            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        })
    }


      fun glideDownload(context: Context, url: String,downloadCall:(File?)->Unit) {
        Glide.with(context).downloadOnly().load(url).addListener(object : RequestListener<File> {
            override fun onLoadFailed(
                e: GlideException?,
                model: Any?,
                target: Target<File>,
                isFirstResource: Boolean
            ): Boolean {
                downloadCall.invoke(null)
                return false
            }

            override fun onResourceReady(
                resource: File,
                model: Any,
                target: Target<File>?,
                dataSource: DataSource,
                isFirstResource: Boolean
            ): Boolean {
                downloadCall.invoke(resource)

                return false
            }

        }).preload()
    }


    suspend fun parseJsonStr(string: String): MutableList<NewBean> {
        var data: MutableList<NewBean> = mutableListOf()
        val jsonArray = JSONArray(string)
        for (h in 0 until jsonArray.length()) {
            val jsonObject = jsonArray[h] as JSONObject
            jsonObject.run {
                val id = getString("categoryId")
                val listArray = getJSONArray("list")
                var listData: MutableList<NewBeanChild> = mutableListOf()
                for (d in 0 until listArray.length()) {
                    val listBean = listArray.get(d) as JSONObject
                    listBean.run {
                        val newBeanChild = NewBeanChild(
                            classId = id, mp3Url = getString("mp3Url"),
                            preUrl = getString("preUrl"),
                            title = getString("title")
                        )
                        listData.add(
                            newBeanChild
                        )
                        MyRoomBase.dataBase.getNewBeanChildDao().insertData(newBeanChild)
                    }
                }

                val newBean = NewBean(
                    categoryUrl = getString("categoryUrl"),
                    categoryId = id, categoryName = getString("categoryName")
                )
                data.add(
                    newBean
                )
                MyRoomBase.dataBase.getNewBeanDao().insertData(newBean)
            }


        }
        return data
    }
}