package xyz.myachin.saveto.ui.sharing.direct

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import xyz.myachin.saveto.R
import xyz.myachin.saveto.logic.intent.ACCESS_DOCUMENTS_CODE
import xyz.myachin.saveto.logic.intent.ACTION_GET_ACCESS_FOR_DOCUMENTS
import xyz.myachin.saveto.settings.Settings

class DirectFileSaveDocumentsActivity : DirectFileSaveBaseActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (intent == null || intent.action.isNullOrBlank() || intent.type.isNullOrBlank()) {
            Toast.makeText(
                applicationContext,
                "Unexpected intent!11. File not saved",
                Toast.LENGTH_LONG
            ).show()
            finishHim()
            return
        }
        verifyNeedResetUri()
        handleIntent(intent)
    }

    override fun verifyNeedResetUri() {
        if (needResetUri(Settings.documentUri)) {
            Toast.makeText(
                applicationContext,
                getString(R.string.lost_directory_access, getString(R.string.documents_title)),
                Toast.LENGTH_SHORT
            ).show()
            Settings.documentUri = null
        }
    }

    private fun handleIntent(intent: Intent) {
        if (Settings.documentUri == null) {
            startActivityForResult(
                createAccessRequest(intent, ACTION_GET_ACCESS_FOR_DOCUMENTS),
                ACCESS_DOCUMENTS_CODE
            )
            return
        }
        super.handleIntent(intent, Settings.documentUri!!)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (RESULT_OK == resultCode) {
            Settings.documentUri = data?.data
            handleIntent(getRequestIntent())
        }
        finishHim()
    }
}