package ir.mnpc.rasadyar

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.core.content.FileProvider
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import java.io.File
import androidx.core.net.toUri

class MainActivity : FlutterActivity() {

    private val CHANNEL = "apk_installer"
    private val INSTALL_PACKAGES_REQUEST_CODE = 1001
    private val installer = ApkInstaller(this)
    private val TAG = "cj"

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        MethodChannel(
            flutterEngine.dartExecutor.binaryMessenger,
            CHANNEL
        ).setMethodCallHandler { call, result ->
            if (call.method == "apk_installer") {
                val internalFile =  File(context.filesDir.parentFile, "app_flutter/rasadyar.apk")
                val externalFile = File(context.getExternalFilesDir(null), "rasadyar.apk")

                internalFile.copyTo(externalFile, overwrite = true)
                if (!installer.canInstallPackages()) {
                    installer.pendingApkFile = externalFile
                    installer.requestInstallPermission(activity)
                } else {
                    installer.installApk(externalFile)
                }
                result.success(null)
            }
        }


    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == ApkInstaller.INSTALL_PERMISSION_REQUEST_CODE) {
            if (installer.canInstallPackages() && installer.pendingApkFile != null) {
                installer.installApk(installer.pendingApkFile!!)
                installer.pendingApkFile = null
            }
        }
    }
}
