package xyz.myachin.saveto.ui.sharing

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.provider.DocumentsContract
import androidx.appcompat.app.AppCompatActivity
import xyz.myachin.saveto.logic.intent.*
import xyz.myachin.saveto.settings.Settings
import xyz.myachin.saveto.ui.alerts.getDebugAlertDialog
import xyz.myachin.saveto.ui.alerts.getInconsistentOnActivityResult
import xyz.myachin.saveto.ui.alerts.getNotAccessToDirectoryAlert
import xyz.myachin.saveto.ui.alerts.getUnexpectedRequestCode

class RequestAccessToFolderActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (intent == null || intent.action.isNullOrEmpty()) {
            finishHim()
            return
        }

        handleIntent(intent)
    }

    private fun handleIntent(intent: Intent) {
        val requestIntent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)

        val code = when (intent.action) {
            ACTION_GET_ACCESS_FOR_DOCUMENTS -> {
                addType(requestIntent, AccessTypes.DOCUMENT)
                ACCESS_DOCUMENTS_CODE
            }

            ACTION_GET_ACCESS_FOR_IMAGES -> {
                addType(requestIntent, AccessTypes.IMAGE)
                ACCESS_IMAGES_CODE
            }

            ACTION_GET_ACCESS_FOR_VIDEOS -> {
                addType(requestIntent, AccessTypes.VIDEO)
                ACCESS_VIDEOS_CODE
            }

            ACTION_GET_ACCESS_FOR_ARCHIVES -> {
                addType(requestIntent, AccessTypes.ARCHIVE)
                ACCESS_ARCHIVES_CODE
            }

            else -> {
                getDebugAlertDialog(this) { _, _ -> finishHim() }.show()
                return
            }
        }
        startActivityForResult(requestIntent, code)
    }

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

        if (data == null || data.data == null) {
            getInconsistentOnActivityResult(this) { _, _ -> finishHim() }.show()
            return
        }

        when (requestCode) {
            ACCESS_DOCUMENTS_CODE -> {
                when (resultCode) {
                    RESULT_CANCELED -> {
                        createRequestAlert(ACTION_GET_ACCESS_FOR_DOCUMENTS)
                    }
                    RESULT_OK -> {
                        contentResolver.takePersistableUriPermission(
                            data.data!!,
                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                        )
                        Settings.documentUri = data.data!!
                        finishHim()
                    }
                }
            }
            ACCESS_IMAGES_CODE -> {
                when (resultCode) {
                    RESULT_CANCELED -> {
                        createRequestAlert(ACTION_GET_ACCESS_FOR_IMAGES)
                    }
                    RESULT_OK -> {
                        contentResolver.takePersistableUriPermission(
                            data.data!!,
                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                        )
                        Settings.imageUri = data.data!!
                        finishHim()
                    }
                }
            }
            ACCESS_VIDEOS_CODE -> {
                when (resultCode) {
                    RESULT_CANCELED -> {
                        createRequestAlert(ACTION_GET_ACCESS_FOR_VIDEOS)
                    }
                    RESULT_OK -> {
                        contentResolver.takePersistableUriPermission(
                            data.data!!,
                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                        )
                        Settings.videoUri = data.data!!
                        finishHim()
                    }
                }
            }
            ACCESS_ARCHIVES_CODE -> {
                when (resultCode) {
                    RESULT_CANCELED -> {
                        createRequestAlert(ACTION_GET_ACCESS_FOR_ARCHIVES)
                    }
                    RESULT_OK -> {
                        contentResolver.takePersistableUriPermission(
                            data.data!!,
                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                        )
                        Settings.archiveUri = data.data!!
                        finishHim()
                    }
                }
            }
            else -> {
                getUnexpectedRequestCode(this) { _, _ -> finishHim() }.show()
                return
            }
        }
    }

    private fun addType(requestIntent: Intent, accessType: AccessTypes) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
        when (accessType) {
            AccessTypes.DOCUMENT -> {
                requestIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, "text/plain")
            }

            AccessTypes.IMAGE -> {
                requestIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, "image/png")
            }

            AccessTypes.VIDEO -> {
                requestIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, "video/mp4")
            }

            AccessTypes.ARCHIVE -> {
                requestIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, "application/zip")
            }

            else -> {
                getDebugAlertDialog(this) { _, _ -> finishHim() }.show()
            }
        }
    }

    private fun createRequestAlert(action: String) {
        getNotAccessToDirectoryAlert(this,
            { _, _ -> handleIntent(Intent(action)) },
            { _, _ -> finishHim() })
            .show()
    }

    private fun finishHim() {
        finish()
    }
}