package com.zxhyis.toolss.logic

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import android.view.View
import android.widget.Toast
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.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import androidx.recyclerview.widget.DiffUtil
import com.zxhyis.toolss.FileApp
import com.zxhyis.toolss.ad.EventHelper
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?>, flag: Int? = null) {
    val intent = Intent(this, T::class.java).apply {
        flag?.let { addFlags(it) }
    }
    intent.putExtras(bundleOf(*params))
    startActivity(intent)
}

fun View.setOnClick(className: String, action: (view: View) -> Unit) {

    this.setOnClickListener {
        var idString = ""
        runCatching {
            idString = this.context.resources.getResourceEntryName(this.id)
        }
        EventHelper.event("viewClick_${className}_$idString")
        action(this)
    }
}

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

const val TEST_MODE = false

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

interface Logic {
    fun doLogic()
}

interface DialogDismissListener {
    fun onDialogDismissed()
}

interface ClickCallBack {
    fun clickBack(fileName: String)
}

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 shareMultipleImagesAndVideos(
    imageUris: ArrayList<Uri>,
    context: Context
) {
    val intent = Intent().apply {
        action = Intent.ACTION_SEND_MULTIPLE
        putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris)
        type = "*/*"
    }
    context.startActivity(Intent.createChooser(intent, "Share image and video"))
}

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 shareZipFile(zipFilePath: String, context: Context) {
    val zipFile = File(zipFilePath)
    val uri = FileProvider.getUriForFile(context, "${context.packageName}.provider", zipFile)

    val shareIntent = Intent().apply {
        action = Intent.ACTION_SEND
        putExtra(Intent.EXTRA_STREAM, uri)
        type = "application/zip"
        addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    }

    context.startActivity(Intent.createChooser(shareIntent, "Share Folder"))
}

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

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



