package xyz.myachin.saveto.ui.supports

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import xyz.myachin.saveto.logic.intent.*
import xyz.myachin.saveto.settings.Settings

class AskDirAccessActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (intent.getIntExtra(EXTRA_DIRECTORY_ACCESS_NEED, -1) > -1) {
            start(intent.getIntExtra(EXTRA_DIRECTORY_ACCESS_NEED, -1))
        } else {
            setResult(RESULT_CANCELED)
            finish()
        }
    }

    private fun start(accessCode: Int) {
        startActivityForResult(IntentCreator.forDirectSaving(accessCode), accessCode)
    }

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

        if (resultCode != RESULT_OK) {
            finish()
            return
        }
        data?.data?.run {
            contentResolver.takePersistableUriPermission(this,
                Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)

            when (requestCode) {
                ACCESS_VIDEOS_CODE -> Settings.videoUri = this
                ACCESS_IMAGES_CODE -> Settings.imageUri = this
                ACCESS_DOCUMENTS_CODE -> Settings.documentUri = this
                ACCESS_ARCHIVES_CODE -> Settings.archiveUri = this
            }
        }
        finish()
    }

}