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_ARCHIVES_CODE
import xyz.myachin.saveto.logic.intent.ACTION_GET_ACCESS_FOR_ARCHIVES
import xyz.myachin.saveto.settings.Settings

class DirectFileSaveArchivesActivity : 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.archiveUri)) {
            Toast.makeText(
                applicationContext,
                getString(R.string.lost_directory_access, getString(R.string.archives_title)),
                Toast.LENGTH_SHORT
            ).show()
            Settings.archiveUri = null
        }
    }

    private fun handleIntent(intent: Intent) {
        if (Settings.archiveUri == null) {
            startActivityForResult(
                createAccessRequest(intent, ACTION_GET_ACCESS_FOR_ARCHIVES),
                ACCESS_ARCHIVES_CODE
            )
            return
        }
        super.handleIntent(intent, Settings.archiveUri!!)
    }

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