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

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

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

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

    private fun handleIntent(intent: Intent) {
        if (Settings.imageUri == null) {
            startActivityForResult(
                createAccessRequest(intent, ACTION_GET_ACCESS_FOR_IMAGES),
                ACCESS_IMAGES_CODE
            )
            return
        }
        super.handleIntent(intent, Settings.imageUri!!)
    }

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

}