package xyz.myachin.saveto.ui.share.fake

import android.app.Activity
import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import xyz.myachin.saveto.R
import xyz.myachin.saveto.settings.Settings
import xyz.myachin.saveto.ui.notification.ResetDefaultsNotification
import xyz.myachin.saveto.ui.share.direct.DirectShareActivity
import xyz.myachin.saveto.ui.share.manual.ManualShareActivity

class ActionViewActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        Thread {
            if (packageManager
                    .resolveActivity(Intent(Intent.ACTION_VIEW).apply {
                        type = intent.type
                    },
                        PackageManager.MATCH_DEFAULT_ONLY)?.activityInfo?.packageName == packageName &&
                Settings.preventBeDefault
            ) {
                ResetDefaultsNotification(applicationContext).reset()
            }
        }.start()

        if (isSdcard(intent.data)) {
            intent.component = null
            val chooser = Intent.createChooser(intent, getString(R.string.choose_target)).apply {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    putExtra(Intent.EXTRA_EXCLUDE_COMPONENTS,
                        arrayOf(ComponentName.createRelative(applicationContext.packageName,
                            ActionViewActivity::class.java.name)))
                }
            }
            startActivity(chooser)
        } else {
            startActivity(intent.apply {
                action = Intent.ACTION_SEND
                setClassName(packageName,
                    if (Settings.actionViewManual) ManualShareActivity::class.java.name else DirectShareActivity::class.java.name)
                putExtra(Intent.EXTRA_STREAM, data)
            })
        }
    }

    private fun isSdcard(uri: Uri?): Boolean {
        val storages = arrayOf(
            "/storage/emulated/",
            "/media/external/",
            ".externalstorage.",
            "com.mobisystems.fileman.RemoteFiles",
            "com.github.axet.filemanager",
            "/external_files/",
            "com.google.android.apps.nbu.files.provider",
            "com.ghostsq.commander.FileProvider/FS/",
        )
        uri?.let {
            storages.forEach { storage ->
                if (uri.toString().replace("%2F", "/").contains(storage)) return true
            }
        }
        return false
    }

    override fun onRestart() {
        super.onRestart()
        finish()
    }
}