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

import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.util.Log
import android.widget.Toast
import androidx.documentfile.provider.DocumentFile
import xyz.myachin.saveto.R
import xyz.myachin.saveto.logic.DIRECT_SAVE
import xyz.myachin.saveto.logic.file.FileProcessor
import xyz.myachin.saveto.logic.intent.*
import xyz.myachin.saveto.logic.url.UrlProcessor
import xyz.myachin.saveto.ui.sharing.RequestAccessToFolderActivity
import xyz.myachin.saveto.ui.sharing.supports.NeedDownloaderActivity

abstract class DirectFileSaveBaseActivity : Activity() {
    private lateinit var mFileProcessor: FileProcessor
    private lateinit var mUrlProcessor: UrlProcessor
    private lateinit var mSavedIntent: Intent

    protected fun createAccessRequest(intent: Intent, action: String): Intent {
        Toast.makeText(applicationContext, R.string.set_directory_first, Toast.LENGTH_SHORT).show()
        mSavedIntent = intent
        return Intent(action).run {
            setClassName(applicationContext, RequestAccessToFolderActivity::class.java.name)
        }
    }

    fun getRequestIntent() = mSavedIntent

    protected open fun handleIntent(intent: Intent, uri: Uri) {
        if (intent.type == null) {
            Toast.makeText(
                applicationContext,
                "NULL mime type!11 File not saved",
                Toast.LENGTH_LONG
            ).show()
            Log.e(DIRECT_SAVE, "Unexpected null mime type")
            finishHim()
            return
        }

        val intentProcessor = IntentProcessor(intent)

        when (intentProcessor.getContentTypeForIntent()) {
            ContentType.FILE, ContentType.TEXT, ContentType.BAD_URL -> {
                mFileProcessor = FileProcessor(intentProcessor)
                DocumentFile.fromTreeUri(applicationContext, uri)?.let { treeUri: DocumentFile ->
                    treeUri.createFile(intent.type!!, intentProcessor.getFileName())
                        ?.let { documentFile ->
                            mFileProcessor.prepareOutput(documentFile.uri, contentResolver)
                            mFileProcessor.writeFile()
                        }
                }
                mFileProcessor.getRemoveFileIntent()?.run {
                    startActivity(this)
                }
            }

            ContentType.GOOD_URL -> {
                mUrlProcessor = UrlProcessor(intentProcessor)
                try {
                    startActivity(mUrlProcessor.processGoodUrl().putExtra(EXTRA_DIRECT, true))
                } catch (_: ActivityNotFoundException) {
                    startActivityForResult(
                        Intent(
                            applicationContext,
                            NeedDownloaderActivity::class.java
                        ).apply {
                            action = ACTION_NEED_DOWNLOAD
                        }, NEED_DOWNLOADER_CODE
                    )
                }
            }

            ContentType.DAMAGED -> {
                Toast.makeText(applicationContext, R.string.damaged_intent, Toast.LENGTH_LONG)
                    .show()
            }

            ContentType.UNKNOWN -> {
                Toast.makeText(
                    applicationContext,
                    getString(R.string.cannot_process_this, getString(R.string.app_name)),
                    Toast.LENGTH_LONG
                ).show()
            }
        }
        finishHim()
    }

    abstract fun verifyNeedResetUri()

    protected fun needResetUri(uri: Uri?): Boolean {
        uri?.run {
            DocumentFile.fromTreeUri(applicationContext, uri)?.run {
                return !canWrite()
            }
            return true
        }
        return false
    }

    protected fun finishHim() {
        finish()
    }
}