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

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

        if (intent == null || intent.action.isNullOrBlank() || (intent.type?.startsWith("video/") != 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.videoUri)) {
            Toast.makeText(
                applicationContext,
                getString(R.string.lost_directory_access, getString(R.string.video_title)),
                Toast.LENGTH_SHORT
            ).show()
            Settings.videoUri = null
        }
    }

    private fun handleIntent(intent: Intent) {
        if (Settings.videoUri == null) {
            startActivityForResult(
                createAccessRequest(intent, ACTION_GET_ACCESS_FOR_VIDEOS),
                ACCESS_VIDEOS_CODE
            )
            return
        }
        super.handleIntent(intent, Settings.videoUri!!)
    }

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