package xyz.myachin.saveto.ui.share.manual

import android.content.Intent
import android.os.Bundle
import android.provider.DocumentsContract
import androidx.core.net.toUri
import xyz.myachin.saveto.logic.intent.*
import xyz.myachin.saveto.ui.share.BaseShareActivity

class ManualShareActivity : BaseShareActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        if (intent.action != Intent.ACTION_SEND) return

        super.onCreate(savedInstanceState)
        processIntent(intent)
    }

    override fun createDownloaderIntent(): Intent {
        return IntentCreator.forDownloader(intent!!.getStringExtra(Intent.EXTRA_TEXT)!!)
            .putExtra(EXTRA_DIRECT, false)
    }

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

        when (requestCode) {
            REQUEST_CREATE_FILE_CODE -> {
                when (resultCode) {
                    RESULT_OK -> {
                        val target = data?.data
                        if (target != null) {
                            return processOnActivityResult(ACCESS_ALREADY_GIVEN,
                                RESULT_OK,
                                Intent().apply { this.data = target })
                        }
                    }
                }
            }
            REQUEST_NEED_DOWNLOADER_CODE -> processOnActivityResult(requestCode, resultCode, data)
            else -> finish()
        }
    }

    override fun requestTarget(intent: IncomingIntent) {
        val saveIntent = IntentCreator.forManualSaving(intent)
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O && tmpFile != null) {
            saveIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, tmpFile!!.toUri())
        }
        startActivityForResult(saveIntent, REQUEST_CREATE_FILE_CODE)
    }
}