package com.example.modifier.utils

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.telephony.SmsManager
import android.telephony.SmsMessage
import android.util.Log
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider.getUriForFile
import com.example.modifier.BuildConfig
import com.example.modifier.MainActivity.Companion.TAG
import com.example.modifier.Utils
import com.example.modifier.constants.PACKAGE_CLEAN_SMS
import com.example.modifier.constants.PACKAGE_MESSAGING
import com.example.modifier.constants.PACKAGE_TELEPHONY
import com.example.modifier.extension.kill
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream

fun injectOTP(otp: String) {
    if (ROOT_ACCESS && false) {
        val intent = Intent()
        intent.setAction("com.example.modifier.sms")
        intent.putExtra("sender", "3538")
        intent.putExtra("message", "Your Messenger verification code is G-$otp")
        val context = getContext()
        context.sendBroadcast(intent)
    } else {
        val context = getContext()
        val smsManager = context.getSystemService("sms") as SmsManager
        smsManager.injectSmsPdu(
            createFakeSms("3538", "Your Messenger verification code is G-$otp"),
            SmsMessage.FORMAT_3GPP, null
        )
    }
}

fun smsIntent(to: String, body: String?, img: File?): Intent {
    val intent = Intent(Intent.ACTION_SENDTO)
    intent.data = Uri.parse("sms:$to")
    if (body?.isNotBlank() == true) {
        intent.putExtra("sms_body", body)
    }
    intent.putExtra("exit_on_sent", true)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    intent.setPackage(PACKAGE_MESSAGING)
    if (img != null) {
        val context = getContext()
        val contentUri: Uri =
            getUriForFile(
                context,
                "${BuildConfig.APPLICATION_ID}.fileprovider",
                img
            )
        intent.putExtra(Intent.EXTRA_STREAM, contentUri)
        context.grantUriPermission(
            PACKAGE_MESSAGING,
            contentUri,
            Intent.FLAG_GRANT_READ_URI_PERMISSION
        )
    }
    return intent
}

fun isOldVersion(context: Context): Boolean {
    val info = context.packageManager.getPackageInfo(PACKAGE_MESSAGING, 0)
    var oldVersion = false
    if (info != null) {
        if (info.versionCode < 170545910) {
            oldVersion = true
        }
    }
    return oldVersion
}

suspend fun clearConv() {
    try {
        val context = getContext()
        val packageManager = context.packageManager
        try {
            packageManager.getPackageInfo(PACKAGE_CLEAN_SMS, 0)
        } catch (e: Exception) {
            Log.wtf(TAG, "clearConv: error", e)
            val apkFile = File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                "cleanSms.apk"
            )
            val fileOutputStream =
                withContext(Dispatchers.IO) {
                    FileOutputStream(apkFile)
                }
            fileOutputStream.use {
                context.assets.open("cleanSms.apk").copyTo(it)
                Log.i(TAG, "clean sms apk copied to $apkFile")
                shellRun(
                    "cp ${apkFile.path} /data/local/tmp/cleanSms.apk",
                    "pm install -r /data/local/tmp/cleanSms.apk", "sleep 1"
                )
            }
        }

        packageManager.getLaunchIntentForPackage(PACKAGE_CLEAN_SMS)?.let {
            shellRun("cmd role add-role-holder android.app.role.SMS $PACKAGE_CLEAN_SMS")
            context.startActivity(
                it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                    .putExtra("clean", true)
            )
            delay(3000)
            shellRun("cmd role add-role-holder android.app.role.SMS $PACKAGE_MESSAGING")
        }

        if (ROOT_ACCESS) {
            val sqlite3 = sqlite3path()

            shellRun(
                "$sqlite3 /data/data/$PACKAGE_MESSAGING/databases/bugle_db \"DELETE FROM conversations;\"",
                "$sqlite3 /data/data/$PACKAGE_MESSAGING/databases/bugle_db \"DELETE FROM messages;\"",
                "$sqlite3 /data/data/$PACKAGE_MESSAGING/databases/bugle_db \"DELETE FROM rcs_remote_capabilities_cache;\"",
            )
            shellRun(PACKAGE_MESSAGING.kill())
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }

    fun installCleanSms() {
        val imageDir = ContextCompat.getExternalFilesDirs(getContext(), "images")[0]
    }
}