package com.zxhyis.tools.logic

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.core.content.ContextCompat.startActivity
import androidx.core.content.FileProvider
import androidx.core.os.bundleOf
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.SharedPreferencesMigration
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import androidx.recyclerview.widget.DiffUtil
import com.zxhyis.tools.FileApp
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import java.io.File
import java.io.IOException

inline fun <reified T : Activity> Context.startActivity(vararg params: Pair<String, Any?>) {
    val intent = Intent(this, T::class.java)
    intent.putExtras(bundleOf(*params))
    startActivity(intent)
}

fun View.setOnClick(action: () -> Unit) {
    this.setOnClickListener { action() }
}

fun String.showToast(duration: Int = Toast.LENGTH_SHORT) {
    Toast.makeText(FileApp.fContext, this, duration).show()
}

const val TEST_MODE = true

fun testLog(msg: String) {
    if (TEST_MODE) {
        Log.d(Counts.TAG_LOG, msg)
    }
}

interface Logic {
    fun doLogic()
}

interface ClickCallBack {
    fun clickBack()
}

interface OnItemClickListener{
    fun onItemClick(file: File)
}

class FileDiffCallback(
    private val oldList: List<ApkInfoBean>,
    private val newList: List<ApkInfoBean>
) : DiffUtil.Callback() {
    override fun getOldListSize(): Int {
        return oldList.size
    }

    override fun getNewListSize(): Int {
        return newList.size
    }

    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldList[oldItemPosition] == newList[newItemPosition]
    }

    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldList[oldItemPosition] == newList[newItemPosition]
    }

}

fun shareImage(imageUri: Uri, context: Context) {
    val shareIntent = Intent().apply {
        action = Intent.ACTION_SEND
        putExtra(Intent.EXTRA_STREAM, imageUri)
        type = "image/*"
    }
    context.startActivity(Intent.createChooser(shareIntent, "Share image"))
}

fun shareMultipleImages(
    imageUris: ArrayList<Uri>,
    context: Context
) {
    val intent = Intent().apply {
        action = Intent.ACTION_SEND_MULTIPLE
        putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris)
        type = "image/*"
    }
    context.startActivity(Intent.createChooser(intent, "Share image"))
}

fun shareMultipleVideos(
    videoUris: ArrayList<Uri>,
    context: Context
) {
    val intent = Intent().apply {
        action = Intent.ACTION_SEND_MULTIPLE
        putParcelableArrayListExtra(Intent.EXTRA_STREAM, videoUris)
        type = "video/*"
    }
    context.startActivity(Intent.createChooser(intent, "Share video"))
}

fun shareAudio(imageUri: Uri, context: Context) {
    val shareIntent = Intent().apply {
        action = Intent.ACTION_SEND
        putExtra(Intent.EXTRA_STREAM, imageUri)
        type = "audio/*"
    }
    context.startActivity(Intent.createChooser(shareIntent, "Share image"))
}

fun shareMultipleAudios(
    audioFiles:List<File>,
    context: Context
) {
    val shareIntent = Intent().apply {
        action = Intent.ACTION_SEND_MULTIPLE
        type = "audio/*"
        putParcelableArrayListExtra(Intent.EXTRA_STREAM, ArrayList<Uri>().apply {
            // 将文件转换为Uri并添加到Intent
            audioFiles.forEach { file ->
                val fileUri = FileProvider.getUriForFile(
                    context,
                    "${context.applicationContext.packageName}.provider",
                    file
                )
                add(fileUri)
            }
        })
        addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    }
    context.startActivity(Intent.createChooser(shareIntent, "Share audio files"))
}

fun shareMultipleApks(
    apkFiles: List<File>,
    context: Context
){
    val shareIntent = Intent().apply {
        action = Intent.ACTION_SEND_MULTIPLE
        type = "application/vnd.android.package-archive"
        putParcelableArrayListExtra(Intent.EXTRA_STREAM, ArrayList<Uri>().apply {
            apkFiles.forEach { apkFile ->
                val apkUri = FileProvider.getUriForFile(context, "${context.applicationContext.packageName}.provider", apkFile)
                add(apkUri)
            }
        })
        addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    }
    context.startActivity(Intent.createChooser(shareIntent, "Share APKs"))
}

fun setStatusBarTextDark(activity: Activity) {
    activity.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
}
fun setStatusBarTextLight(activity: Activity) {
    activity.window.decorView.systemUiVisibility = 0
}


private const val USER_PREFERENCES_NAME = "settings"

val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
    name = USER_PREFERENCES_NAME,
    produceMigrations = { context ->
        listOf(SharedPreferencesMigration(context, USER_PREFERENCES_NAME))
    }
)

object FileDS {
    suspend fun <T> putData(context: Context, data: T, key: Preferences.Key<T>) {
        context.dataStore.edit { preferences ->
            preferences[key] = data
        }
    }

    fun <T> getData(context: Context, key: Preferences.Key<T>, defaultValue: T): Flow<T> {
        return context.dataStore.data
            .catch { exception ->
                if (exception is IOException) {
                    emit(emptyPreferences())
                } else {
                    throw exception
                }
            }
            .map { preferences ->
                preferences[key] ?: defaultValue
            }
    }

    suspend fun clearOneData(context: Context, key: String) {
        context.dataStore.edit {
            it.remove(stringPreferencesKey(key))
        }
    }

    suspend fun clearAllData(context: Context) {
        context.dataStore.edit {
            it.clear()
        }
    }


}
